current position:Home>Android Jetpack component ViewModel

Android Jetpack component ViewModel

2023-01-25 11:31:10Cloud valley area people

ViewModel 概览

ViewModel概览https://developer.android.google.cn/topic/libraries/architecture/viewmodel
ViewModel Class is to pay attention to the life cycle of way to store and manage relevant data interface.ViewModel 类让数据可在发生屏幕旋转等配置更改后继续留存.
ViewModel的亮点:

数据持久化
Asynchronous callback problem does not cause a memory leak
隔离Model层和View层
Fragments间共享数据

This note mainly analyze the persistence of data is also:

ViewModel类让数据可在发生屏幕旋转等配置更改后继续留存

ViewModel使用

添加依赖

    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'

定义ViewModel

public class MyViewModel extends ViewModel {
    
    
    // There can be any variable
    public int number;

}

使用ViewModel

public class MainActivity extends AppCompatActivity {
    

    private MyViewModel myViewModel;
    private TextView mTextView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myViewModel = new ViewModelProvider(this).get(MyViewModel.class);
        mTextView = findViewById(R.id.text);
        mTextView.setText(myViewModel.number + "");
    }


    public void onTextView(View view) {
    
        myViewModel.number = myViewModel.number + 1;
        mTextView.setText(myViewModel.number + "");
    }
}

运行上面代码以后,When user change configuration such as the screen,ViewModelSave data is not lost;

ViewModel原理分析

至于ViewModelOnline there are a lot of the cause of the data is stored in the content,说白了就是一句话,The above data are stored in public memory;
涉及到两个方法:

  • onRetainNonConfigurationInstance() 是在Activity 销毁的时候 进行存储信息.

  • getLastNonConfigurationInstance() 的作用是获取onRetainNonConfigurationInstance存储的信息.

当屏幕发生旋转的时候 ,会先调用 onRetainNonConfigurationInstance先将数据进行保存,然后再通过 getLastNonConfigurationInstance 将保存的数据获取到.
The inside of the specific code is no longer a list,有兴趣可以自己查看;

copyright notice
author[Cloud valley area people],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2023/025/202301251120395567.html

Random recommended