android - 膨胀包含数据绑定(bind)的 Viewstub

标签 android android-layout android-databinding

我有一个具有这种布局的抽象 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/

相关文章:

android - 使用数据绑定(bind)加载图像

android - 数据绑定(bind) : ObservableField of custom object it is not working properly

android - 在 Android 中实现 switch case 语句的正确方法是什么?

java - 编辑文本验证

android 模拟器 1.5、1.6、2.1 无法解析具有 <?xml 版本 ="1.0"编码 ="Shift-JIS"?> 的 XML 文件

android - Recyclerview item点击波纹效果

android - 在 android 的 CalendarView 小部件中更改选定日期的颜色

android - 布局 View 位于模拟器的左上角

javascript - window.open() 在 Android 上从 setTimeout 调用时返回 undefined

android - 使用数据绑定(bind)库更新 UI