布局代码:
<?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"
tools:context="com.example.dell.mvvmdemo.MainActivity">
<data>
<variable
name="user"
type="com.example.dell.mvvmdemo.User"/>
</data>
<LinearLayout
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="@{user.onClickName}"
android:text="@{user.name}"
android:textSize="20sp"
app:newName ="@{user.newName}"
/>
</LinearLayout>
</layout>
javaBean代码:
public class User {
public ObservableField<String> name = new ObservableField<>();
public ObservableField<String> newName = new ObservableField<>();
public void onClickName(View view) {
Log.i("User", name.get());
}
@BindingAdapter({"newName"})
public static void setNewName(TextView tv, ObservableField<String> oName) {
tv.setText(oName.get());
}
}
数据绑定:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
final User user = new User();
user.name.set("zhangsan");
binding.setUser(user);
new Thread(new Runnable() {
@Override
public void run() {
SystemClock.sleep(2000);
user.name.set("lisi");
user.newName.set("wangwu");
}
}).start();
}
}
求问为什么会报错:
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> java.lang.RuntimeException: Found data binding errors.
****/ data binding error ****msg:Cannot find the setter for attribute 'app:newName' with parameter type java.lang.String on android.widget.TextView.
file:F:\Android\MVVMDemo\app\src\main\res\layout\activity_main.xml
loc:24:28 - 24:39
****\ data binding error ****
彩色的沙漠
相关分类