详解Android MVVM模式使用

前言:

MVVM是Model-View-ViewModel的简写。它本质上就是MVC 的改进版。MVVM 就是将其中的View 的状态和行为抽象化,让我们将视图 UI 和业务逻辑分开。当然这些事 ViewModel 已经帮我们做了,它可以取出 Model 的数据同时帮忙处理 View 中由于需要展示内容而涉及的业务逻辑


工程目录结构:


详解Android MVVM模式使用_第1张图片


使用步骤:


1.在项目app的Build下添加:
apply plugin: 'com.android.application'
android { compileSdkVersion 26 buildToolsVersion "27.0.3" dataBinding{ enabled true }
.......
}


2.BaseObservable数据绑定,新建一个JavaBean:
public class Student extends BaseObservable {
    private String name;
    private String age;

    private String header;

    public String getHeader() {
        return header;
    }

    public void setHeader(String header) {
        this.header = header;
    }

    public Student(String header, String name, String age) {
        this.name = name;
        this.age = age;
        this.header = header;
    }
    @Bindable
    public String getName() {
        return name;
    }


    public void setName(String name) {
        this.name = name;
        notifyPropertyChanged(com.example.mvvm.BR.name);
    }
    @Bindable
    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
        notifyPropertyChanged(com.example.mvvm.BR.age);
    }

    /**
     * 自定义属性:提供一个静态方法来加载image
     *
     * @param view
     * @param url
     */
    @BindingAdapter("bind:header")
    public static void getImage(ImageView view, String url) {
        Picasso.with(view.getContext()).load(url).into(view);
    }


    public void click(View view) {
        Toast.makeText(view.getContext(), getName(), Toast.LENGTH_SHORT).show();
    }

}



3.创建CommAdapter适配器
public class CommAdapter<T> extends BaseAdapter {

    private Context context;
    private LayoutInflater inflater;
    private int layoutId;
    /**
     * variable的ID自动生成
     */
    private int variableId;

    private List<T> list;

    public CommAdapter(Context context, LayoutInflater inflater, int layoutId, int variableId, List<T> list) {
        this.context = context;
        this.inflater = inflater;
        this.layoutId = layoutId;
        this.variableId = variableId;
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewDataBinding dataBinding;
        if(convertView==null){
            dataBinding= DataBindingUtil.inflate(inflater,layoutId,parent,false);
        }else{
            /**
             * 重用之前的convertView
             */
            dataBinding=DataBindingUtil.getBinding(convertView);
        }
        dataBinding.setVariable(variableId,list.get(position));
        return dataBinding.getRoot().getRootView();
    }
}


 note:

variableId 编译自动生成,如下:
  详解Android MVVM模式使用_第2张图片



4.item_pattern.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="student"
            type="com.example.mvvm.Student" />
    data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ImageView
            android:layout_width="150dp"
            android:layout_height="100dp"
            app:header="@{student.header}" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@{student.name}" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:onClick="@{student.click}"
            android:text="@{student.age}" />

    LinearLayout>

layout>


5.MainActivity测试调用
public class MainActivity extends AppCompatActivity {
    ListView list;
    List<Student> data=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        list= (ListView) findViewById(R.id.listView);
        data.add(new Student("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1528871063802&di=9e8faa6eb45eccc8f678be6797159a71&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimgad%2Fpic%2Fitem%2F9d82d158ccbf6c8154bdd5ccb63eb13533fa4008.jpg","1","1"));
        data.add(new Student("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1528871063802&di=9e8faa6eb45eccc8f678be6797159a71&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimgad%2Fpic%2Fitem%2F9d82d158ccbf6c8154bdd5ccb63eb13533fa4008.jpg","2","2"));
        data.add(new Student("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1528871063802&di=9e8faa6eb45eccc8f678be6797159a71&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimgad%2Fpic%2Fitem%2F9d82d158ccbf6c8154bdd5ccb63eb13533fa4008.jpg","3","3"));
        list.setAdapter(new CommAdapter<Student>(this,getLayoutInflater(),R.layout.item_pattern, BR.student,data));
    }
}


运行效果:

详解Android MVVM模式使用_第3张图片

你可能感兴趣的:(Android架构)