我读到了android data binding并希望在我的应用程序中使用它, 但我在xml布局阶段失败了。
我有activity_main.xml
这样:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
</data>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/tab1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="@layout/tab1"/>
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</layout>
和tab1.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
<EditText
...
我想将数据绑定应用到最后EditText
,但是如果我插入
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
</data>
<TabHost>
...
这会导致
activity_main.xml:9: AAPT: Error parsing XML: duplicate attribute
问题是,我应该如何在包含的布局中组合数据绑定和TabHost
绑定EditText
?
答案 0 :(得分:2)
这是您的提示XML: duplicate attribute
。它甚至会在错误消息9中告诉您一个行号,它大致位于TabHost元素中。
现在,哪个XML属性重复了?命名空间(xmlns:android
)
删除布局标记
中不在XML最顶层元素的那个答案 1 :(得分:1)
问题出在xmlns:android
只需删除此xmlns:android="http://schemas.android.com/apk/res/android"
及其完成。
关于DataBinding
,我不这么认为你甚至已经实现了它,除了那个标签
在<data>
activity_main.xml
<data>
<variable
name="name"
type="String"/>
</data>
使用包含的布局
传递它<include layout="@layout/tab1"
app:name="@{name}"/>
现在在tab1.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="name"
type="String"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/edit1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_row="0"
android:ems="1"
android:inputType="text"
android:text="@{name}" />
</LinearLayout>
</layout>
你差不多完成了,现在你只需要在你的活动中实现绑定
ActivityMainBinding binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
binding.setName("Email Address");
答案 2 :(得分:0)
我在这里可以看到两个错误,您使用xmlns
名称空间两次,tab1
ID两次。删除一个名称空间,然后更改ID。
<LinearLayout
android:id="@+id/tab1" /* you used tab1 here as id*/
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="@layout/tab1"/> /* you used tab1 here as id */