最近在学习DataBinding,在这里记录下学习的轨迹
收获:
1代码解耦。
2少些很多没有营养的代码,美观度高!
遇坑:
1官方文档 https://developer.android.com/topic/libraries/data-binding/index.html#listener_bindings 写的真是简单,
只提供码片段,需要结合博客和别的资料一齐看,才大概明白其中的奥妙。
2不容易定位错误。编译通过,无法安装。请看上篇文章 https://blog.csdn.net/qq_35599978/article/details/80028278
3如果绑定数据的XML需要增加
我手动build ,clean,sync project,或者删掉.build文件,再sync project,还是不管用,只能关掉studio,再打开,你发现
世界真美好。我的studio version 3.1
Activity主页布局代码
RecyclerView Item 布局代码
点击事件的接口
public interface ItemClick {
void onClicked(View veiw, User user);
}
Activitie 代码
public class ScrollingActivity extends AppCompatActivity {@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityScrolling2Binding binding = DataBindingUtil.setContentView(this, R.layout.activity_scrolling2);
UserBean bean = new UserBean("andry","13years","swimming");
binding.setUserbean(bean);
bean.setName("new_name");
binding.recycleVeiw.setAdapter(new UserAdapter(new ItemClick() {
@Override
public void onClicked(View veiw, User user) {
Snackbar.make(veiw, user.getName(), Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
}));
binding.recycleVeiw.setLayoutManager(new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL,false));
}
}
adapter 对应的bean
public class User extends BaseObservable {public User(String name, @DrawableRes int res) {
this.name = name;
this.res = res;
}String name;
public@Bindable int res;
@Bindable
public String getName() {
return name;
}public void setName(String name) {
this.name = name;
notifyPropertyChanged(BR.name);
}public void setRes(int res) {
this.res = res;
}public User getData() {
return this;
}
}
adapter对应的代码
public class UserAdapter extends RecyclerView.Adapter
activity对应的viewmodel
publicclass UserBean{
public String name,age,hobby;
public String getName() {
return name;
}public String getAge() {
return age;
}public void setAge(String age) {
this.age = age;
}public String getHobby() {
return hobby;
}public void setHobby(String hobby) {
this.hobby = hobby;
}public UserBean(String name, String age, String hobby) {
this.name = name;
this.age = age;
this.hobby = hobby;
}public void setName(String name) {
this.name = name;
//notifyPropertyChanged(BR.userbean);
}
}
【Android开发|DataBinding 绑定Recyclerview及点击事件】
推荐阅读
- 从零开发一个完整的Android项目(九)——图片浏览
- Android开发|ViewPager自适应高度问题
- Android|Android 指定销毁一个Activity
- 【Android】简单图片浏览器
- 理解ButterKnife(自动生成绑定资源的代码)
- MAC下搭建Android Studio
- NestedScrollingParent 和NestedScrollingChild 实现嵌套滑动
- android用shape画一条横线
- 华为推送 的坑
- Duplicate class com.alipay.a.a.a found in modules classes.jar (:alipaySdk-15.6.2-20190416165036:) an