ViewModel is simple to use

viewmodel : Manage interface-related data in a life cycle-oriented way, obtain and retain necessary information for Activity/Fragment

The viewModel is led out by the following example. The interface is as follows. There are three controls in the interface, the top is a score, and the two buttons below do +1 and +3 operations on the score respectively.
Insert picture description here
MainActivity

/**
 * 普通mvc写法实现
 */
public class MainActivity extends AppCompatActivity {
    
    

    private TextView textView;
    private Button button1;
    private Button button2;
    private ScoreModel scoreModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(null);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textView);
        button1 = findViewById(R.id.button1);
        button2 = findViewById(R.id.button2);
        scoreModel = new ScoreModel();
        textView.setText(String.valueOf(scoreModel.getScore()));

        button1.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                scoreModel.addScore(1);
                textView.setText(String.valueOf(scoreModel.getScore()));
            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                scoreModel.addScore(2);
                textView.setText(String.valueOf(scoreModel.getScore()));
            }
        });
    }

}


ScoreModel entity class

/**
 * 普通实体类
 */
public class ScoreModel {
    
    
    private int score = 0;

    public int getScore() {
    
    
        return score;
    }

    public void addScore(int n) {
    
    
        this.score += n;
    }
}

Layout file activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="32dp"
        android:text="0"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.21" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="+2"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.461" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="+1"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.32" />
</androidx.constraintlayout.widget.ConstraintLayout>

The running effect is as follows: when the
Insert picture description here
app is switched to the background, when the memory is tight, the phone kills the process in order to save power, the user manually changes the phone configuration (such as phone language) or app settings, and then opens the app, the score previously calculated at this time becomes 0 ; The effect is as follows

Insert picture description here
Previously, the interface data cache was saved in the onSaveInstanceState method, and the bundle was judged in the onRestoreInstanceState method or the onCreate method, and the value was echoed; with the viewmodel, it is much simpler

Add the MyMainModel class to inherit ViewModel and replace the ScoreModel just now. The code is as follows

/**
 * ViewModel测试类
 */
public class MainViewModel1 extends ViewModel {
    
    
    private int score = 0;

    public int getScore() {
    
    
        return score;
    }

    public void addScore(int n) {
    
    
        this.score += n;
    }
}


Add dependency

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

The changed MainActivity, other unchanged

/**
 * ViewModel测试类
 */
public class MainActivity1 extends AppCompatActivity {
    
    

    private TextView textView;
    private Button button1;
    private Button button2;
    private MainViewModel1 viewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(null);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textView);
        button1 = findViewById(R.id.button1);
        button2 = findViewById(R.id.button2);
        viewModel = ViewModelProviders.of(this).get(MainViewModel1.class);//新版写法可能不同
        textView.setText(String.valueOf(viewModel.getScore()));

        button1.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                viewModel.addScore(1);
                textView.setText(String.valueOf(viewModel.getScore()));
            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                viewModel.addScore(2);
                textView.setText(String.valueOf(viewModel.getScore()));
            }
        });
    }

}


The operation effect is the same as before, now try to switch the system language, and found that the interface data will not be lost, because viewodel helped us to deal with it

Insert picture description here

Only this record, if you have any questions, please point out, thank you

Guess you like

Origin blog.csdn.net/nongminkouhao/article/details/114992335