Android(数据管理)-ViewModel&liveData&DataBinding

ViewModel

创建类

package com.example.navigationdemo;

import androidx.lifecycle.ViewModel;

public class MyViewModel extends ViewModel {
    public int num = 0;
}

在acvivity 反射获取

//通过反射拿到对象
        myViewModel = new ViewModelProvider(this).get(MyViewModel.class);

类中属性变量自己定义

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //通过反射拿到对象
        myViewModel = new ViewModelProvider(this).get(MyViewModel.class);
        button=findViewById(R.id.button2);
        textView = findViewById(R.id.textView4);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myViewModel.num++;
                textView.setText(String.valueOf(myViewModel.num));
            }
        });



        navController = Navigation.findNavController(this, R.id.fragment);
        //actionBar 左上角后退键
        NavigationUI.setupActionBarWithNavController(this, navController);

    }

 liveData 

新建  ViewModelLiveData 类

package com.example.navigationdemo;

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

public class ViewModelLiveData extends ViewModel {
    //管理数据
    private MutableLiveData<Integer> mutableLiveData;
    
    public MutableLiveData<Integer> getMutableLiveData() {
        //默认值
        if (mutableLiveData == null) {
            this.mutableLiveData = new MutableLiveData<Integer>();
            mutableLiveData.setValue(0);

        }
        return mutableLiveData;
    }

    public void setMutableLiveData(MutableLiveData<Integer> mutableLiveData) {
        this.mutableLiveData = mutableLiveData;
    }
     
    public void addMutableLiveData(int i) {
        mutableLiveData.setValue(mutableLiveData.getValue()+i);
    }
}

acvivity

变量自己定义

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //通过反射拿到对象
        viewModelLiveData = new ViewModelProvider(this).get(ViewModelLiveData.class);
        button=findViewById(R.id.button2);
        textView = findViewById(R.id.textView4);
        //监听数据变化 如果变化,就会触发 onChange 变化
        viewModelLiveData.getMutableLiveData().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                textView.setText(String.valueOf(integer));
            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewModelLiveData.addMutableLiveData(1);

            }
        });



     

    }

DataBinding 双向绑定

设置的bulid.gradle

 dataBinding {
        enabled = true
    }

 

 

定义ViewModel

package com.example.navigationdemo;

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

public class ViewModelLiveData extends ViewModel {
    //管理数据
    private MutableLiveData<Integer> mutableLiveData;
    public MutableLiveData<Integer> getMutableLiveData() {
        //默认值
        if (mutableLiveData == null) {
            this.mutableLiveData = new MutableLiveData<Integer>();
            mutableLiveData.setValue(0);

        }
        return mutableLiveData;
    }
    public void setMutableLiveData(MutableLiveData<Integer> mutableLiveData) {
        this.mutableLiveData = mutableLiveData;
    }
    //执行方法
    public void addMutableLiveData() {
        mutableLiveData.setValue(mutableLiveData.getValue()+1);
    }
}

activity.xml

选中 <?xml version="1.0" encoding="utf-8"?> 第一行 alt+enter

会被layout 标签包裹,出现data标签

type 用来绑定viewModel

使用参数 @{String.valueOf(data.mutableLiveData)}  

String.valueOf() 只是为了用java 语法转成字符串

调用方法   android:onClick="@{()->data.addMutableLiveData()}"

<?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">

    <data>
        <variable
            name="data"
            type="com.example.navigationdemo.ViewModelLiveData" />

    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="@{()->data.addMutableLiveData()}"
            android:text="@string/buttonM"
            app:layout_constraintBottom_toBottomOf="@+id/fragment"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.591" />

        <TextView
            android:id="@+id/textView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{String.valueOf(data.mutableLiveData)}"
            app:layout_constraintBottom_toTopOf="@+id/button2"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

Activity.java

package com.example.navigationdemo;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.NavigationUI;
import android.os.Bundle;
import com.example.navigationdemo.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {
  
    ViewModelLiveData viewModelLiveData;
    ActivityMainBinding mainBinding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // setContentView(R.layout.activity_main);
        //dataBinding 渲染activity.xml 返回值可以获取组件
        mainBinding=  DataBindingUtil.setContentView(this, R.layout.activity_main);
        //通过反射拿到对象
        viewModelLiveData = new ViewModelProvider(this).get(ViewModelLiveData.class);
        //绑定viewModel
        mainBinding.setData(viewModelLiveData);
        //监听自我
        mainBinding.setLifecycleOwner(this);
       
    }

   
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yzhSWJ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值