是否可以在 onCreate() 中加载我的 main.xml 布局文件,然后在应用程序中切换到新的 XML 布局?我稍后尝试将 setContentView() 放置在应用程序中,但这似乎并没有真正设置新 View ,因为我对新设置的 xml 布局文件中对象的引用返回为 null。我试过使用 LayoutInflater 做一些布局膨胀,但我没有运气(我可能做错了什么)......
那么有没有其他方法可以在运行时交换 layout xml 布局呢? 谢谢!
最佳答案
您可以将您的布局放在一个 xml 文件中。您不想立即看到的那些,在 XML 中设置 android:visibility="gone"
,然后在运行时调用 hiddenView.setVisibility(View.VISIBLE) ;
。
您的 XML 看起来像这样:
<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>
在运行时你可以这样做:
layout1.setVisibility(View.GONE);
layout2.setVisibility(View.VISIBLE);
这实际上会创建布局交换的外观。
我相信如果您在两个布局之间共享对象,这也会起作用。只需确保首先使用 android:id="@+id/view1"
设置 id,然后每次设置此 id 时,您都将执行 android:id="@id/view1"
(没有 +)。
<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>
关于android - 是否可以在 Android 运行时交换 XML 布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3345026/