【发布时间】:2016-05-19 14:47:16
【问题描述】:
我在 FrameLayout 中使用 ViewStub,以便在第一次打开应用程序时使用教程视图对其进行填充。
我的活动.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
...
<ViewStub
android:id="@+id/introHolder"
android:inflatedId="@+id/introHolder"
android:layout="@layout/intro_landing1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
我正在膨胀的视图称为intro_landing1.xml,它是一个RelativeLayout。
intro_landing1.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent" android:background="@color/opaqBlack30"
android:id="@+id/introView1"
android:tag="RelativeLayoutIntroViewTag">
<!--...-->
</RelativeLayout>
在我的 Activity onCreate 中,我使用了两种不同的方法来为 ViewStub 充气,但它们都不起作用(我看不到 intro_landing1 视图)。
第一种方法 - 设置可见性:
if(!previouslyStarted){
((ViewStub) findViewById(R.id.introHolder)).setVisibility(View.VISIBLE);
}
第二种方法 - 膨胀 ViewStub:
ViewStub introStub = (ViewStub) findViewById(R.id.introHolder);
introStub.setLayoutResource(R.layout.intro_landing1);
View inflatedView = introStub.inflate();
使用第二种方法,我通过执行 inflatedView.getTag 记录了返回的视图(inflatedView),它返回了 intro_landing1 RelativeLayout 的标签“RelativeLayoutIntroViewTag”,因此实际上返回了视图,但我没有看到它。
为了确保在视图树层次结构中正确定位 ViewStub,我在 Activity.xml 中使用了 <include/> 标记,而不是像这样的 ViewStub:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
...
<!-- <ViewStub
android:id="@+id/introHolder"
android:inflatedId="@+id/introHolder"
android:layout="@layout/intro_landing1"
android:layout_width="match_parent"
android:layout_height="match_parent" />-->
<include layout="@layout/intro_landing1"/>
</FrameLayout>
这行得通。
为什么在可见性变化或膨胀后不显示 ViewStub?
谢谢!
【问题讨论】:
-
首选方式是致电
inflate -
谢谢,我编辑了这个问题。简而言之:没有任何改变
-
你检查了
inflate调用返回值的内容吗? -
是的,我打印了 ViewStub.inflate() 返回的 View 的 View.getTag() ,这是我为 intro_landing1 RelativeLayout 设置的标签。
-
@tynn 感谢您的反馈,我重写了问题。希望它更容易理解。
标签: android xml android-layout viewstub