我有一个具有这种布局的抽象 BaseActivity
类:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize" />
<ViewStub
android:id="@+id/activity_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
应用程序中的所有 Activity 都扩展了 BaseActivity 并覆盖了一个名为 getLayoutResID
的方法,以提供其在 ViewStub
中膨胀的布局资源 ID。我这样做是为了避免在每个布局中都有工具栏。用于膨胀布局的基类中的代码是这样的:
private void setupLayout() {
setContentView(R.layout.activity_base);
ViewStub viewStub = (ViewStub) findViewById(R.id.activity_layout);
viewStub.setLayoutResource(getLayoutResID());
viewStub.inflate();
}
我的一项 Activity 使用新的 Data Binding系统,在其布局下方:
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="user" type="com.myapp.User" />
</data>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{user.name}" />
</layout>
虽然数据绑定(bind)工作得很好,但问题是工具栏不可见。知道为什么数据绑定(bind)引擎会删除/隐藏此 Activity 中的工具栏吗?
最佳答案
ViewStubs 需要特别注意,因为它们在膨胀时会自行替换,而不是自行填充。 在 data-binding/guide#viewstubs 上阅读更多内容
另一个解决方案(完全避免 ViewStub
)是让您的 ConcreteActivities
在其布局中包含工具栏布局 - 而不是膨胀包含工具栏的 stub 。如果您想为 Activity 使用自定义工具栏,您也不会那么头疼。
关于android - 膨胀包含数据绑定(bind)的 Viewstub,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31947721/