支持SharedPreference等使用到Application的相关
因为 SharedPreference 需要使用到 Application 来获取到,所以要想配合ViewModel还需要传入Application作为参数,当然,Jetpack已经为我们准备好了
AndroidViewModel:感知应用上下文的ViewModel,它继承自ViewModel。
下面以一个非常简单的实例来说明
因为使用dataBinding以及SharedPreference需要在build.grade中添加依赖
1 apply plugin: ‘com.android.application‘ 2 3 android { 4 compileSdkVersion 29 5 buildToolsVersion "29.0.2" 6 defaultConfig { 7 applicationId "com.example.viewmodelshp" 8 minSdkVersion 19 9 targetSdkVersion 29 10 versionCode 1 11 versionName "1.0" 12 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 13 } 14 buildTypes { 15 release { 16 minifyEnabled false 17 proguardFiles getDefaultProguardFile(‘proguard-android-optimize.txt‘), ‘proguard-rules.pro‘ 18 } 19 } 20 dataBinding.enabled true 21 } 22 23 dependencies { 24 implementation fileTree(dir: ‘libs‘, include: [‘*.jar‘]) 25 implementation ‘androidx.appcompat:appcompat:1.0.2‘ 26 implementation ‘androidx.constraintlayout:constraintlayout:1.1.3‘ 27 testImplementation ‘junit:junit:4.12‘ 28 androidTestImplementation ‘androidx.test.ext:junit:1.1.0‘ 29 androidTestImplementation ‘androidx.test.espresso:espresso-core:3.1.1‘ 30 implementation ‘androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-alpha02‘ 31 implementation ‘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类 13 private SavedStateHandle handle; 14 private String key = getApplication().getResources().getString(R.string.data_key); 15 private String shpName = getApplication().getResources().getString(R.string.shp_name); 16 17 public MyViewModel(@NonNull Application application, SavedStateHandle handle) { 18 super(application); 19 this.handle = handle; 20 if (!handle.contains(key)) { 21 load(); 22 } 23 } 24 25 public LiveData<Integer> getNumber() { 26 return handle.getLiveData(key); 27 } 28 29 private void load() { 30 SharedPreferences shp = getApplication().getSharedPreferences(shpName, Context.MODE_PRIVATE); 31 int x = shp.getInt(key, 0); 32 handle.set(key, x); 33 } 34 35 private void save() { 36 SharedPreferences shp = getApplication().getSharedPreferences(shpName, Context.MODE_PRIVATE); 37 SharedPreferences.Editor editor = shp.edit(); 38 editor.putInt(key, getNumber().getValue()); 39 editor.apply(); 40 } 41 42 public void add(int x) { 43 handle.set(key, getNumber().getValue() + x); 44 save(); 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 { 13 MyViewModel myViewModel; 14 ActivityMainBinding binding; 15 16 @Override 17 protected void onCreate(Bundle savedInstanceState) { 18 super.onCreate(savedInstanceState); 19 setContentView(R.layout.activity_main); 20 binding = DataBindingUtil.setContentView(this, R.layout.activity_main); 21 ViewModelProviders.of(this, new SavedStateViewModelFactory(this)).get(MyViewModel.class); 22 binding.setData(myViewModel); 23 binding.setLifecycleOwner(this); 24 } 25 }
布局如下
1 <?xml version="1.0" encoding="utf-8"?> 2 <layout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 xmlns:tools="http://schemas.android.com/tools"> 5 6 <data> 7 <variable 8 name="data" 9 type="com.example.viewmodelshp.MyViewModel" /> 10 </data> 11 12 <androidx.constraintlayout.widget.ConstraintLayout 13 android:layout_width="match_parent" 14 android:layout_height="match_parent" 15 tools:context=".MainActivity"> 16 17 <TextView 18 android:layout_width="wrap_content" 19 android:layout_height="wrap_content" 20 android:layout_marginLeft="8dp" 21 android:layout_marginTop="8dp" 22 android:layout_marginRight="8dp" 23 android:layout_marginBottom="8dp" 24 android:text="@{String.valueOf(data.getNumber)}" 25 android:textSize="40sp" 26 app:layout_constraintBottom_toBottomOf="parent" 27 app:layout_constraintLeft_toLeftOf="parent" 28 app:layout_constraintRight_toRightOf="parent" 29 app:layout_constraintTop_toTopOf="parent" 30 app:layout_constraintVertical_bias="0.35" 31 tools:text="100" /> 32 33 <Button 34 android:id="@+id/button" 35 android:layout_width="wrap_content" 36 android:layout_height="wrap_content" 37 android:layout_marginStart="8dp" 38 android:layout_marginTop="8dp" 39 android:layout_marginEnd="8dp" 40 android:layout_marginBottom="8dp" 41 android:onClick="@{()->data.add(1)}" 42 android:text="@string/button_plus" 43 android:textSize="18sp" 44 app:layout_constraintBottom_toBottomOf="parent" 45 app:layout_constraintEnd_toEndOf="parent" 46 app:layout_constraintHorizontal_bias="0.2" 47 app:layout_constraintStart_toStartOf="parent" 48 app:layout_constraintTop_toTopOf="parent" 49 app:layout_constraintVertical_bias="0.5" /> 50 51 <Button 52 android:id="@+id/button2" 53 android:layout_width="wrap_content" 54 android:layout_height="wrap_content" 55 android:layout_marginStart="8dp" 56 android:layout_marginTop="8dp" 57 android:layout_marginEnd="8dp" 58 android:layout_marginBottom="8dp" 59 android:onClick="@{()->data.add(-1)}" 60 android:text="@string/button_mius" 61 android:textSize="18sp" 62 app:layout_constraintBottom_toBottomOf="parent" 63 app:layout_constraintEnd_toEndOf="parent" 64 app:layout_constraintHorizontal_bias="0.8" 65 app:layout_constraintStart_toStartOf="parent" 66 app:layout_constraintTop_toTopOf="parent" 67 app:layout_constraintVertical_bias="0.5" /> 68 69 </androidx.constraintlayout.widget.ConstraintLayout> 70 </layout>
在这个例子里通过获取SharedPreference来存储数据,再配合LiveData,SaveStataHandler实现跨越整个App的生命周期同步。