我正在尝试从main_activity.xml设置customView的变量(buttonText),但出现此错误:
属性buttonText(aka com.example.testbinding:buttonText)不 找到了。错误:链接文件资源失败。
customView.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" >
<data>
<variable
name="buttonText"
type="String" />
</data>
<LinearLayout
android:id="@+id/container"
android:orientation="vertical">
<Button
android:id="@+id/button"
android:text="@{buttonText}" />
</LinearLayout>
</layout>
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
</data>
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.example.testbinding.CustomView
android:id="@+id/customView"
...
app:buttonText = "Test button text"
...
>
</com.example.testbinding.CustomView>
</android.support.constraint.ConstraintLayout>
</layout>
在此post中,我发现:
在“自定义视图”中,对布局进行充气,但是通常情况下, 为您要设置的属性提供设置器:
我的CustomView类具有buttonText属性的公共设置器:
public class CustomView extends LinearLayout {
private CustomViewBinding binding;
private String buttonText;
public CustomView(Context context) {
super(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
binding = DataBindingUtil.inflate(inflater, R.layout.custom_view, this, true);
}
public String getButtonText() {
return buttonText;
}
public void setButtonText(String buttonText) {
this.buttonText = buttonText;
}
}
谁能告诉我这是怎么回事? 还是没有BindingAdapter就不可能?
答案 0 :(得分:0)
binding.setbuttonText(“ text_button”);
代替
public String getButtonText() {
return buttonText;
}
public void setButtonText(String buttonText) {
this.buttonText = buttonText;
}
答案 1 :(得分:0)
似乎我发现了什么问题。
如果我使用在父视图中声明的变量-一切正常。但是,如果我在财产中使用价值权利,那是行不通的。
错误:
app:buttonText = "Test button text"
app:progressValue = "50"
正确:
<variable
name="viewModel"
type="com.example.testbinding.ViewModel"/>
app:buttonText = "@{viewModel.buttonText}"
app:progressValue = "@{viewModel.progressValue}"
当然,viewModel必须为这些属性定义一个设置器。