Android : ViewModel+LiveData observe观察数据 改变内容简单应用

observe观察数据  改变内容

1.导包

// 使用androidx版本库
    implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0-alpha03'
     // 或者,使用support版本库
    implementation 'android.arch.lifecycle:extensions:1.1.1'

2.继承ViewModel

package com.example.mylivedata;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

//需要改变的数据
public class MyViewModel extends ViewModel {
    private MutableLiveData  data;

    public MutableLiveData getData() {
        if(data == null){
            data = new MutableLiveData<>();
            data.setValue(0);
        }
        return data;
    }

    public void addNumberData(int num){
        data.setValue(data.getValue() + num);
    }
}

3.使用 

package com.example.mylivedata;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

public class MainActivity extends AppCompatActivity {

    private TextView textView;
    private ImageView imgZan,imgCai;
    private MyViewModel myViewModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.tv_content);
        imgZan = findViewById(R.id.img_zan);
        imgCai =findViewById(R.id.img_cai);

        myViewModel= ViewModelProviders.of(this).get(MyViewModel.class);

        //观察自己
        myViewModel.getData().observe(this, new Observer() {
            @Override
            public void onChanged(Integer integer) {
                //内容发生改变
                textView.setText(String.valueOf(integer));
            }
        });

        //绑定事件
        imgZan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myViewModle.addNumberData(1);
            }
        });

        imgCai.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myViewModle.addNumberData(-1);
            }
        });
    }
}

你可能感兴趣的:(Android,相关,android,笔记)