Android Jetpack -- ViewModel篇

业无高卑志当坚,男儿有求安得闲?这篇文章主要讲述Android Jetpack -- ViewModel篇相关的知识,希望能为你提供帮助。
支持SharedPreference等使用到Application的相关【Android Jetpack -- ViewModel篇】因为 SharedPreference 需要使用到 Application 来获取到,所以要想配合ViewModel还需要传入Application作为参数,当然,Jetpack已经为我们准备好了
androidViewModel:感知应用上下文的ViewModel,它继承自ViewModel。


下面以一个非常简单的实例来说明
因为使用dataBinding以及SharedPreference需要在build.grade中添加依赖

1 apply plugin: ‘com.android.application‘ 2 3 android { 4compileSdkVersion 29 5buildToolsVersion "29.0.2" 6defaultConfig { 7applicationId "com.example.viewmodelshp" 8minSdkVersion 19 9targetSdkVersion 29 10versionCode 1 11versionName "1.0" 12testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 13} 14buildTypes { 15release { 16minifyEnabled false 17proguardFiles getDefaultProguardFile(‘proguard-android-optimize.txt‘), ‘proguard-rules.pro‘ 18} 19} 20dataBinding.enabled true 21 } 22 23 dependencies { 24implementation fileTree(dir: ‘libs‘, include: [‘*.jar‘]) 25implementation ‘androidx.appcompat:appcompat:1.0.2‘ 26implementation ‘androidx.constraintlayout:constraintlayout:1.1.3‘ 27testImplementation ‘junit:junit:4.12‘ 28androidTestImplementation ‘androidx.test.ext:junit:1.1.0‘ 29androidTestImplementation ‘androidx.test.espresso:espresso-core:3.1.1‘ 30implementation ‘androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-alpha02‘ 31implementation ‘androidx.lifecycle:lifecycle-extensions:2.1.0‘ 32 }

构造MyViewModel.java
1 package com.example.viewmodelshp; 2 3 import android.app.Application; 4 import android.content.Context; 5 import android.content.SharedPreferences; 6 7 import androidx.annotation.NonNull; 8 import androidx.lifecycle.AndroidViewModel; 9 import androidx.lifecycle.LiveData; 10 import androidx.lifecycle.SavedStateHandle; 11 12 public class MyViewModel extends AndroidViewModel {//继承AndroidViewModel类 13private SavedStateHandle handle; 14private String key = getApplication().getResources().getString(R.string.data_key); 15private String shpName = getApplication().getResources().getString(R.string.shp_name); 16 17public MyViewModel(@NonNull Application application, SavedStateHandle handle) { 18super(application); 19this.handle = handle; 20if (!handle.contains(key)) { 21load(); 22} 23} 24 25public LiveData< Integer> getNumber() { 26return handle.getLiveData(key); 27} 28 29private void load() { 30SharedPreferences shp = getApplication().getSharedPreferences(shpName, Context.MODE_PRIVATE); 31int x = shp.getInt(key, 0); 32handle.set(key, x); 33} 34 35private void save() { 36SharedPreferences shp = getApplication().getSharedPreferences(shpName, Context.MODE_PRIVATE); 37SharedPreferences.Editor editor = shp.edit(); 38editor.putInt(key, getNumber().getValue()); 39editor.apply(); 40} 41 42public void add(int x) { 43handle.set(key, getNumber().getValue() + x); 44save(); 45} 46 47 }

MainActivity.java
1 package com.example.viewmodelshp; 2 3 import android.os.Bundle; 4 5 import androidx.appcompat.app.AppCompatActivity; 6 import androidx.databinding.DataBindingUtil; 7 import androidx.lifecycle.SavedStateViewModelFactory; 8 import androidx.lifecycle.ViewModelProviders; 9 10 import com.example.viewmodelshp.databinding.ActivityMainBinding; 11 12 public class MainActivity extends AppCompatActivity { 13MyViewModel myViewModel; 14ActivityMainBinding binding; 15 16@Override 17protected void onCreate(Bundle savedInstanceState) { 18super.onCreate(savedInstanceState); 19setContentView(R.layout.activity_main); 20binding = DataBindingUtil.setContentView(this, R.layout.activity_main); 21ViewModelProviders.of(this, new SavedStateViewModelFactory(this)).get(MyViewModel.class); 22binding.setData(myViewModel); 23binding.setLifecycleOwner(this); 24} 25 }

布局如下
1 < ?xml version="1.0" encoding="utf-8"?> 2 < layout xmlns:android="http://schemas.android.com/apk/res/android" 3xmlns:app="http://schemas.android.com/apk/res-auto" 4xmlns:tools="http://schemas.android.com/tools"> 5 6< data> 7< variable 8name="data" 9type="com.example.viewmodelshp.MyViewModel" /> 10< /data> 11 12< androidx.constraintlayout.widget.ConstraintLayout 13android:layout_width="match_parent" 14android:layout_height="match_parent" 15tools:context=".MainActivity"> 16 17< TextView 18android:layout_width="wrap_content" 19android:layout_height="wrap_content" 20android:layout_marginLeft="8dp" 21android:layout_marginTop="8dp" 22android:layout_marginRight="8dp" 23android:layout_marginBottom="8dp" 24android:text="@{String.valueOf(data.getNumber)}" 25android:textSize="40sp" 26app:layout_constraintBottom_toBottomOf="parent" 27app:layout_constraintLeft_toLeftOf="parent" 28app:layout_constraintRight_toRightOf="parent" 29app:layout_constraintTop_toTopOf="parent" 30app:layout_constraintVertical_bias="0.35" 31tools:text="100" /> 32 33< Button 34android:id="@+id/button" 35android:layout_width="wrap_content" 36android:layout_height="wrap_content" 37android:layout_marginStart="8dp" 38android:layout_marginTop="8dp" 39android:layout_marginEnd="8dp" 40android:layout_marginBottom="8dp" 41android:onClick="@{()-> data.add(1)}" 42android:text="@string/button_plus" 43android:textSize="18sp" 44app:layout_constraintBottom_toBottomOf="parent" 45app:layout_constraintEnd_toEndOf="parent" 46app:layout_constraintHorizontal_bias="0.2" 47app:layout_constraintStart_toStartOf="parent" 48app:layout_constraintTop_toTopOf="parent" 49app:layout_constraintVertical_bias="0.5" /> 50 51< Button 52android:id="@+id/button2" 53android:layout_width="wrap_content" 54android:layout_height="wrap_content" 55android:layout_marginStart="8dp" 56android:layout_marginTop="8dp" 57android:layout_marginEnd="8dp" 58android:layout_marginBottom="8dp" 59android:onClick="@{()-> data.add(-1)}" 60android:text="@string/button_mius" 61android:textSize="18sp" 62app:layout_constraintBottom_toBottomOf="parent" 63app:layout_constraintEnd_toEndOf="parent" 64app:layout_constraintHorizontal_bias="0.8" 65app:layout_constraintStart_toStartOf="parent" 66app:layout_constraintTop_toTopOf="parent" 67app:layout_constraintVertical_bias="0.5" /> 68 69< /androidx.constraintlayout.widget.ConstraintLayout> 70 < /layout>

在这个例子里通过获取SharedPreference来存储数据,再配合LiveData,SaveStataHandler实现跨越整个App的生命周期同步。

    推荐阅读