1.AndroidViewModel简介
“Application context aware ViewModel
.
Subclasses must have a constructor which accepts Application
as the only parameter.”
AndroidViewModel是感知应用程序上下文的ViewModel。子类必须有一个接受Application作为唯一参数的构造函数。
2.示例代码
2.1创建项目
创建AndroidViewModelSample项目。
2.2 创建MyAndroidViewModel
创建MyAndroidViewModel。
package com.gaoting.androidviewmodelsample;
import android.app.Application;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
public class MyAndroidViewModel extends AndroidViewModel {
public MyAndroidViewModel(@NonNull Application application) {
super(application);
Toast.makeText(application,"hello,I'm AndroidViewModel.",Toast.LENGTH_SHORT).show();
}
}
2.3创建ViewModelFactory
创建ViewModelFactory类。
package com.gaoting.androidviewmodelsample;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
public class ViewModelFactory implements ViewModelProvider.Factory {
Application mAapp;
public ViewModelFactory(Application app) {
this.mAapp = app;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
if(modelClass.isAssignableFrom(MyAndroidViewModel.class)){
return (T) new MyAndroidViewModel(mAapp);
}
return null;
}
}
2.4修改MainActivity
修改MainActivity类。关键方法:ViewModelFactory就是2.3创建的工厂类。
ViewModelProvider viewModelProvider = new ViewModelProvider(this,new ViewModelFactory(getApplication()));
myAndroidViewModel = viewModelProvider.get(MyAndroidViewModel.class);
package com.gaoting.androidviewmodelsample;
import android.os.Bundle;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.ViewModelProvider;
public class MainActivity extends AppCompatActivity {
MyAndroidViewModel myAndroidViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewModelProvider viewModelProvider = new ViewModelProvider(this,new ViewModelFactory(getApplication()));
myAndroidViewModel = viewModelProvider.get(MyAndroidViewModel.class);
}
}