如何使用Android Databinding获取包含的视图?

Luc*_* S. 8 xml data-binding android android-layout

我正在玩Android数据绑定库,我正试图将它与包含的布局一起使用.

我的代码是这样的:

activity_main.xml中

<layout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:bind="http://schemas.android.com/apk/res-auto">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id = "@+id/linearLayout">

    <include
        layout="@layout/view" />
  </LinearLayout>
</layout>
Run Code Online (Sandbox Code Playgroud)

view.xml用

<View xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id = "@+id/myView">
 </View>
Run Code Online (Sandbox Code Playgroud)

MainActivity.java

public MainActivity extends AppCompatActivity{

  private ActivityMainBinding mBinding;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);

    LinearLayout layout = mBinding.linearLayout; // this field is visible
    View myView  = mBinding.myView // THIS FIELD IS NOT VISIBLE
  }


}
Run Code Online (Sandbox Code Playgroud)

正如我在评论中所写的那样,在"包含"布局中声明的视图myView是不可见的.如果我用view.xml中的实际代码替换,那么mBinding.myView变得可见,原因似乎是包含然后.

官方文件只说明了这一点

"数据绑定不支持include作为合并元素的直接子节点." 但在我看来,View是LinearLayout的孩子,它不是直接的孩子..

任何提示?

Geo*_*unt 19

您需要为include语句提供ID:

<include android:id="@+id/included"
    layout="@layout/view" />
Run Code Online (Sandbox Code Playgroud)

现在您可以访问包含视图:

View myView = mBinding.included;
Run Code Online (Sandbox Code Playgroud)

如果包含的布局是绑定布局,则include将是生成的绑定.例如,如果view.xml是:

<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <View
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@{@android:color/black}"
        android:id="@+id/myView"/>
</layout>
Run Code Online (Sandbox Code Playgroud)

那么布局字段将是一个ViewBinding类:

View myView = mBinding.included.myView;
Run Code Online (Sandbox Code Playgroud)