我为 2 路数据绑定(bind)和接缝制作了一个简单的 hello world 完美工作(在 editext 上编写时,textview 自动更新),但是像官方文档一样在线找到的所有代码都有更多的代码和复杂性,如 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>
特别是文档使用这些东西,但接缝没用:
那么,我的代码有什么问题或缺失?
最佳答案
在双向数据绑定(bind)中,您需要创建从 BaseObservable
扩展的类, 用 @Bindable
注释 getter并调用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
类型的数据绑定(bind)布局变量传递.<?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()
在您的 Activity 中设置此布局变量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(""));
}
}
关于android - 在android上进行双向数据绑定(bind)的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61562501/