我为 2 路数据绑定做了一个简单的 hello world,并且接缝工作完美(当在 editext 上写入时,textview 自动更新),但是像官方文档一样在网上找到的所有代码都有更多的代码和复杂性,例如https://developer.android.com/topic/libraries/data-binding/two-way https://developer.android.com/topic/libraries/data-binding/two-way
这是我的代码:
public class MainActivity extends AppCompatActivity {
public String pippo;
public Boolean visible = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DataBindingUtil.setContentView(this, R.layout.activity_main);
}
}
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="pippo"
type="String" />
<variable
name="visible"
type="Boolean" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@={pippo}" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{pippo}"
android:visibility="@{visible ? android.view.View.VISIBLE: android.view.View.GONE}" />
<CheckBox
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="@={visible}" />
</LinearLayout>
</layout>
特别是文档使用这个东西但接缝无用:
- 基础可观察对象
- @可绑定
- 避免无限循环的代码
- 通知属性更改
那么,我的代码有什么错误或缺失吗?
在双向数据绑定中,您需要创建扩展自的类BaseObservable
,用注释吸气剂@Bindable
并打电话notifyPropertyChanged
在你的设置器中如下:
public class Person extends BaseObservable {
private String name;
Person(String name) {
this.name = name;
}
@Bindable
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
notifyPropertyChanged(BR.name);
}
}
然后将此类作为类型的数据绑定布局变量传递Person
.
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="person"
type="com.example.android......Person" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@={person.name}" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{person.name}" />
</LinearLayout>
</layout>
注意:更改类路径type
属性。
然后在您的活动中设置此布局变量setPerson()
public class ExampleActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DataBindingUtil.setContentView(this, R.layout.activity_example);
ActivityExampleBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_example);
mActivityMainBinding.setPerson(new Person(""));
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)