当前位置: 代码迷 >> 综合 >> DataBinding+ViewModel+LiveData+recyclerview
  详细解决方案

DataBinding+ViewModel+LiveData+recyclerview

热度:50   发布时间:2024-02-13 12:07:14.0

android下加这个

 compileOptions {sourceCompatibility JavaVersion.VERSION_1_8targetCompatibility JavaVersion.VERSION_1_8}dataBinding {enabled = true}

 依赖

  def lifecycle_version = "2.2.0"def arch_version = "2.1.0"// ViewModelimplementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"// LiveDataimplementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"// Lifecycles only (without ViewModel or LiveData)implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"implementation 'com.github.JiJiBo:BugUtils:1.0.8'// Saved state module for ViewModelimplementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"// alternately - if using Java8, use the following instead of lifecycle-compilerimplementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"// optional - helpers for implementing LifecycleOwner in a Serviceimplementation "androidx.lifecycle:lifecycle-service:$lifecycle_version"// optional - ProcessLifecycleOwner provides a lifecycle for the whole application processimplementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"// optional - ReactiveStreams support for LiveDataimplementation "androidx.lifecycle:lifecycle-reactivestreams-ktx:$lifecycle_version"

 

 

    implementation 'com.github.JiJiBo:BugUtils:1.0.8'implementation 'androidx.recyclerview:recyclerview:1.1.0'implementation 'com.qmuiteam:qmui:2.0.0-alpha10'implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'implementation 'io.reactivex.rxjava3:rxjava:3.0.0'implementation 'com.squareup.okhttp3:okhttp:3.10.0'implementation 'com.google.code.gson:gson:2.8.6'implementation 'com.github.bumptech.glide:glide:4.11.0'annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'

 

这是在安卓中使用jectpack,来实现recyclerview,所以就是把数据用条目展示出来

首先实现item所依存的bean,也就是传给adapter的arraylist<Bean> 那个Bean


public class Student {private int age;private String name;public Student() {}public Student(int age, String name) {this.age = age;this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}
}

然后再写item的布局文件

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"><data><variablename="student"type="com.zcf.myshujubangding.Student" /><importalias="deal"type="com.zcf.myshujubangding.DealUtils" /></data><LinearLayoutandroid:layout_width="match_parent"android:layout_height="100dp"android:orientation="horizontal"><TextViewandroid:id="@+id/tv_1"android:layout_width="100dp"android:layout_height="match_parent"android:text="@{student.name}" /><Viewandroid:layout_width="1dp"android:layout_height="match_parent"android:background="#000" /><TextViewandroid:id="@+id/tv_2"android:layout_width="100dp"android:layout_height="match_parent"android:text="@{deal.toString(student.age)}" /><Viewandroid:layout_width="1dp"android:layout_height="match_parent"android:background="#000" /></LinearLayout>
</layout>

这里引进一个东西没有说,就是

DealUtils

他长这样

package com.zcf.myshujubangding;public class DealUtils {public static String toString(int age) {return  age+"";}
}

就是把数字转为字符串这个工具类可以被引进xml

 下面展示适配器怎么写

public class AccountDetailAdapter extends Adapter<AccountDetailAdapter.FenLeiViewHolder> {private ArrayList<Student> datas;public AccountDetailAdapter(ArrayList<Student> datas) {this.datas = datas;}@NonNull@Overridepublic FenLeiViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {//这里注意ItemAccountDetailBinding inflate = DataBindingUtil.inflate(LayoutInflater.from(BugApp.getContext()), R.layout.item_account_detail, parent, false);return new FenLeiViewHolder(inflate.getRoot());}@Overridepublic void onBindViewHolder(@NonNull FenLeiViewHolder holder, final int position) {//这里注意ItemAccountDetailBinding bind = DataBindingUtil.bind(holder.itemView);bind.setStudent(datas.get(position));bind.executePendingBindings();}@Overridepublic int getItemCount() {return datas.size();}protected class FenLeiViewHolder extends RecyclerView.ViewHolder {public FenLeiViewHolder(@NonNull View itemView) {super(itemView);}}}

 下面的工作就是从网络获取数据,存入recycleview

数据用在ViewModel中获取,里面有个获取假数据的方法

public class MainViewModel extends ViewModel {private MutableLiveData<ArrayList<Student>> students;public MainViewModel() {}public MutableLiveData<ArrayList<Student>> getStudents() {if (students == null) {students = new MutableLiveData<>();students.setValue(new ArrayList<Student>());}return students;}public void getFalseData() {ArrayList<Student> ss = new ArrayList<>();ss.add(new Student(12, "f"));ss.add(new Student(32, "d"));ss.add(new Student(12, "e3"));ss.add(new Student(322, "fde"));students.getValue().addAll(ss);}}

还没把主页面的布局文件拿出来

现在拿出来

<?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"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity"><androidx.recyclerview.widget.RecyclerViewandroid:id="@+id/rv"android:layout_width="match_parent"android:layout_height="match_parent"app:bindData="@{rvData}"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent"app:layout_constraintTop_toTopOf="parent" /></LinearLayout><data><importalias="student"type="com.zcf.myshujubangding.Student" /><variablename="rvData"type="java.util.ArrayList&lt;student>"/></data>
</layout>

里面引入了两个数据,recycleview里有个属性,把引入的数据放在里面,这个属性会在恰当的时刻做什么呢

public class RvAdapter {@BindingAdapter("bindData")public static void bindAdapter(RecyclerView rv, ArrayList<Student> datas) {rv.setAdapter(new AccountDetailAdapter(datas));rv.setLayoutManager(new LinearLayoutManager(rv.getContext()));rv.addItemDecoration(new DividerItemDecoration(rv.getContext(), DividerItemDecoration.VERTICAL));}
}

你看,他会把传入的数据和recycleview绑定在一起

重要的看看主页面

class MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)//得到viewmodelval get = ViewModelProviders.of(this).get(MainViewModel::class.java)//得到布局Bindingval contentView =DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)//初始化recycleviewcontentView.rvData = get.students.value//recycleview数据更新的监听get.students.observe(this, object : Observer<ArrayList<Student>> {override fun onChanged(t: ArrayList<Student>?) {if (contentView.rv.adapter != null) {contentView.rv.adapter!!.notifyDataSetChanged()}}})//一个获取数据的方法get.getFalseData()}
}

 

 

 

  相关解决方案