为包含数据绑定的Viewstub充气

Die*_*mar 6 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>
Run Code Online (Sandbox Code Playgroud)

应用程序中的所有活动都扩展了BaseActivity,并覆盖了一个被调用的方法,getLayoutResID以提供在其中膨胀的布局资源ID ViewStub.我这样做是为了避免在每个布局中使用工具栏.基类中用于扩充布局的代码如下:

private void setupLayout() {
    setContentView(R.layout.activity_base);

    ViewStub viewStub = (ViewStub) findViewById(R.id.activity_layout);
    viewStub.setLayoutResource(getLayoutResID());
    viewStub.inflate();
}
Run Code Online (Sandbox Code Playgroud)

我的一个活动使用新的数据绑定系统,在其布局下面:

<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>
Run Code Online (Sandbox Code Playgroud)

尽管数据绑定完美无缺,但问题是ToolBar不可见.知道为什么数据绑定引擎删除/隐藏此活动中的工具栏吗?

Tap*_*boy 1

ViewStub 需要特别注意,因为它们在膨胀时会替换自己,而不是填充自己。阅读更多关于数据绑定/指南#viewstubs

另一个解决方案(完全避免ViewStub)是让您ConcreteActivities在其布局中包含工具栏布局 - 而不是膨胀包含工具栏的存根。如果您想为某个活动使用自定义工具栏,您也不会那么头疼。