我正在玩
Android databinding library,我正在尝试使用它包含布局.
我的代码是这样的:
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>
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>
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 } }
正如我在评论中所写的那样,在“包含”布局中声明的视图myView是不可见的.如果我用view.xml中的实际代码替换,那么mBinding.myView变得可见,原因似乎是包含然后.
官方文件仅说明了这一点
“Data binding does not support include as a direct child of a merge element.”
but in my case View is a child of LinearLayout,it’s not a direct child..
任何提示?
解决方法
您需要为include语句提供ID:
<include android:id="@+id/included" layout="@layout/view" />
现在您可以访问包含视图:
View myView = mBinding.included;
如果包含的布局是绑定布局,则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>
那么布局字段将是一个ViewBinding类:
View myView = mBinding.included.myView;