Android mvvm的dataBinding和的listview
-从网上找了很多mvvm jetpack的例子,但一直没找到在viewmodel中实现listview的列表项目点击的例子,于是我自己想了个办法。先databinding.enabled=true
构建步骤
1,创建实体类
public class Bean {
public String userName;
public Bean(String userName){
this.userName=userName;
}
public void setUserName(String userName) {
this.userName=userName;
}
}
2,创建ViewModel
@SuppressLint("StaticFieldLeak")
public class MainVM extends AndroidViewModel {
Context context;
private ActivityMainBinding binding;
public MainVM(@NonNull Application application) {
super(application);
context=application;
}
public void setBinding(ActivityMainBinding binding){
this.binding=binding;
List<Bean> data=new ArrayList<>();
data.add(new Bean("emm"));
binding.setAdp(new ListViewAdapter(context,data));
}
public static class ListViewAdapter extends ArrayAdapter<Bean> {
Context context;
List<Bean> data;
public ListViewAdapter(Context context, List<Bean> objects){
super(context,R.layout.item,objects);
this.context=context;
data=objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
ViewDataBinding binding;
if (convertView == null) {
binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.item, parent, false);
convertView = binding.getRoot();
convertView.setTag(binding);
} else {
binding = (ViewDataBinding) convertView.getTag();
}
binding.setVariable(BR.adp, data.get(position));
//还是先用找ID的方法把
convertView.findViewById(R.id.itemBtn).setOnClickListener(v -> {
Toast.makeText(context,"123",Toast.LENGTH_SHORT).show();
});
return binding.getRoot();
}
}
}
3,布局以及Listview列表布局item
- Listview布局: activity_main.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">
<data>
<variable
name="adp"
type="com.demo.MainVM.ListViewAdapter" />
<variable
name="vm"
type="com.demo.MainVM" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:adapter="@{adp}"/>
</LinearLayout>
</layout>
- 列表项目布局: item.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<import type="com.demo.Bean" />
<variable
name="user"
type="com.demo.Bean" />
</data>
<LinearLayout
android:id="@+id/itemBtn"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants"
android:orientation="horizontal">
<ImageView
android:src="@mipmap/ic_launcher"
android:layout_width="100dp"
android:layout_height="100dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{`编号:` + user.userName }" />
</LinearLayout>
</layout>
- 用以记录学习进度,所以有别的解决方案吗,这样虽然可行,但我不太清楚解耦效率如何。