# MVVM 基础入门

MVVM 是什么?

MVVM 是 (Model-View-ViewModel)的缩写
MVVM 也是MVC 的架构的一个改进版,
在android中随着项目越来越大,fragment 和activity 变得越来越大,控制器层代码变得臃肿。因此将控制层中的部分代码抽到布局文件里。从而减少控制层臃肿的代码,并且让开发人员很容易的看出那些是动态界面。抽出的动态代码放入ViewModel还方便了开发测试和验证

MVVM.PNG

MVVM的优点

  1. 低耦合 视图(view) 独立于Model 的变化 和修改,并且一个view 可以绑定不同的viewModel
  2. 可重用性 把视图逻辑放在一个viewmodel里面
  3. 独立开发 因为分层每一层的人员不需要了解另外一层的具体实现,所以更容易开发
  4. 可测试性 直接对viewmodle进行测试

MVVM 在android 中的dataBinding 的实现方式

目标: 实现一个播放音蘋的软件
一个主activity托管fragment
一个实际展示界面的fragment

首先在build.gradle(app)文件中加上

dataBinding {
        enabled = true
    }

然修改 layout 中 fragment_beat_box 的 xml文件

<?xml version="1.0" encoding="utf-8"?>

<layout
    xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycleView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="10"
            />
    </LinearLayout>
</layout>

BeatBoxFragment java 代码

public class BeatBoxFragment extends Fragment {

    private BeatBox mBeatBox;

    public static BeatBoxFragment newInstance(){
        return new BeatBoxFragment();
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);

        mBeatBox = new BeatBox(getActivity());
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        FragmentBeatBoxBinding binding = DataBindingUtil
                .inflate(inflater,R.layout.fragment_beat_box,container,false);
        binding.recycleView.setLayoutManager(new GridLayoutManager(getActivity(),3));
        binding.recycleView.setAdapter(new SoundAdapter(mBeatBox.getSounds(),binding));
        return binding.getRoot();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        mBeatBox.relase();
    }

}

关键的代码就是

 FragmentBeatBoxBinding binding = DataBindingUtil
                .inflate(inflater,R.layout.fragment_beat_box,container,false);
        binding.recycleView.setLayoutManager(new GridLayoutManager(getActivity(),3));
        binding.recycleView.setAdapter(new SoundAdapter(mBeatBox.getSounds(),binding));
        return binding.getRoot();
DataBindingUtil.inflate(inflater,R.layout.fragment_beat_box,container,false);// 用于生成与xml对应的绑定对象

FragmentBeatBoxBindg类是系统自动生成的类 它与 fragment_beat_box.xml 文件绑定在一起
那么这个系统生成的类有什么用呢?,他可以直接调取那些有id的控件
例如fragment_beat_box.xml中 recycleView的 id 就是 reycycleView 所以
直接调用 FragmentBeatBoxBinding. reycycleView就行,相当于你直接省去了声明各种控件变量 和findviewbyid 操作的各种麻烦
binding.getRoot()返回的是这个绑定的xml文件生成的view对象

然后我们再来看Recyclview 中的ViewHolder

private class SoundHolder extends RecyclerView.ViewHolder{

       private ListItemSoundBinding mBinding;

       private SoundHolder(ListItemSoundBinding binding){
           super(binding.getRoot());
           mBinding = binding;
           mBinding.setViewModel(new SoundViewModel(mBeatBox));
       }

       public void bind(Sound sound){
           mBinding.getViewModel().setSound(sound);
           mBinding.executePendingBindings();
       }
   }

private class SoundAdapter extends RecyclerView.Adapter<SoundHolder>{

       private List<Sound> mSounds;


       public SoundAdapter(List<Sound> sounds,FragmentBeatBoxBinding mFragmentBeatBoxBinding) {
           mSounds = sounds;
       }

       @NonNull
       @Override
       public SoundHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
           LayoutInflater inflater = LayoutInflater.from(getActivity());
           ListItemSoundBinding binding =DataBindingUtil.inflate(inflater,R.layout.list_item_sound,viewGroup,false);
           return new SoundHolder(binding);
       }

       @Override
       public void onBindViewHolder(@NonNull SoundHolder soundHolder, int i) {
           Sound sound = mSounds.get(i);
           soundHolder.bind(sound);
       }

       @Override
       public int getItemCount() {
           return mSounds.size();
       }
   }

我们看关键代码
mBinding.setViewModel(new SoundViewModel(mBeatBox));
其中mBinding 对象是 和上面一样由DataBindingUtil类由对应的Lis_tItem_SoundBinding.xml文件生成的ListItemSoundBinding 对象

这个对象可以绑定一个由你编写的ViewModel 对象
绑定后可以直接在Lis_tItem_SoundBinding.xml文件中调用

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name="viewModel"
            type="com.example.chl.beatbox.viewmodel.SoundViewModel" />
    </data>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp">

        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:text="@{viewModel.title}"
            tools:text="Sound name"
            android:onClick="@{()-> viewModel.onButtonClicked()}" />
    </FrameLayout>
</layout>

然后在xml中data标签中 variable name 对应的是变量名,然后可以直接调用viewmodel的方法

ViewModel代码

package com.example.chl.beatbox.viewmodel;

import android.databinding.BaseObservable;
import android.databinding.Bindable;

import com.example.chl.beatbox.model.Sound;
import com.example.chl.beatbox.resourceManger.BeatBox;

public class SoundViewModel extends BaseObservable {
    private Sound mSound;
    private BeatBox mBeatBox;
  public SoundViewModel(BeatBox beatBox) {
        mBeatBox = beatBox;
    }
    public Sound getSound() {
        return mSound;
    }

    @Bindable
    public String getTitle(){
        return mSound.getName();
    }

    public void setSound(Sound sound) {
        mSound = sound;
        notifyChange();
    }
    public void onButtonClicked(){
        mBeatBox.play(mSound);
    }
}

关键代码

 @Bindable
    public String getTitle(){
        return mSound.getName();
    }
  
   public void setSound(Sound sound) {
        mSound = sound;
        notifyChange();
    }

@bindable 可以直接实时通知view更新
notifychange()通知刷新所有绑定的数据

主要的代码就是如此

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,902评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,037评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,978评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,867评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,763评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,104评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,565评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,236评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,379评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,313评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,363评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,034评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,637评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,719评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,952评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,371评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,948评论 2 341

推荐阅读更多精彩内容