我测试了它。奇怪!它工作得很好。我在这里发布示例代码,您必须匹配并查找您自己的问题。
活动\ sample.xml
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="response"
type="com.innovanathinklabs.sample.data.Response" />
</data>
<LinearLayout
...
>
<EditText
...
android:text="@={response.data.email}" />
</LinearLayout>
</layout>
Java语言
(父模型)
public class Response extends BaseObservable {
private Data data;
private String message;
private String status;
public void setData(Data data) {
this.data = data;
}
public Data getData() {
return data;
}
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setStatus(String status) {
this.status = status;
}
public String getStatus() {
return status;
}
}
数据爪哇
(子模型)
public class Data extends BaseObservable {
private String userId;
private String lastName;
private String firstName;
private String email;
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserId() {
return userId;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
}
活动示例.java
public class ActivitySample extends AppCompatActivity {
ActivitySampleBinding binding;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_sample);
// make dummy response data
Response response = new Response();
Data data = new Data();
data.setEmail("khermaj@gmail.com");
response.setData(data);
// pass dummy data in layout
binding.setResponse(response);
}
}
*检查事项:
-
检查您的模型是否应扩展
BaseObservable
使用
two-way data binding
. 或者你可以使用
ObservableField
也是。
-
变量名应以小写字母开头。必须检查
Java Naming Convensions
. 你已经带走了
variable name="MyParent"
-
你会得到
NullPointerException
如果尚未将模型传递给布局。像我一样
binding.setResponse(response);
在里面
onCreate()
.