开发者

Is it possible to swap XML layouts during runtime in Android?

Is it possible to load my main.xml layout file in onCreate() and then later in the app, switch to a new开发者_运维知识库 XML layout? I've tried placing setContentView() later on in the app but that seems to not actually set the new View because my references to objects in the newly set xml layout file are returning as null. I've tried doing some layout inflating using the LayoutInflater but I'm having no luck (I'm probably doing something wrong)...

So is there any other way to swap layout xml layouts at runtime? Thanks!


You could have your layouts in a single xml file. The ones you don't want to see immediately, set android:visibility="gone"in the XML, and at runtime you would do a call to hiddenView.setVisibility(View.VISIBLE);.

Your XML would look something like this:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent">
    <LinearLayout android:id="@+id/layout1"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent">
    </LinearLayout>
    <LinearLayout android:id="@+id/layout2"
        android:visibility="gone"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent">
    </LinearLayout>
</RelativeLayout>

at runtime you could do:

layout1.setVisibility(View.GONE);
layout2.setVisibility(View.VISIBLE);

This would essentially create the appearance of the layouts swapping.

I believe this would also work if you have shared objects between the two layouts. Just make sure you set the id first using android:id="@+id/view1" and every subsequent setting of this id you would do android:id="@id/view1" (without the +).

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent">
    <LinearLayout android:id="@+id/layout1"
        android:layout_width="fill_parent">
        <View android:id="@+id/view1"/>
    </LinearLayout>
    <LinearLayout android:id="@+id/layout2"
        android:visibility="gone"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent">
         <View android:id="@id/view1"/>
    </LinearLayout>
</RelativeLayout>


Can't you just create a new activity? Otherwise, I think you might want to look at removing views from the main container and rebuilding your UI trough code. setContentView can only be called once per Activity if I remember well...


I also think that it really sounds like you want a new activity, but I believe you can re-inflate something if you manually delete the existing views and then call getLayoutInflater().inflate(resourceId, rootViewGroup).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜