ViewModel은 사용하기 쉽습니다.

viewmodel : Activity / Fragment에 필요한 정보를 확보하고 유지하기 위해 라이프 사이클 중심의 인터페이스 관련 데이터 관리

예를 들어, 인터페이스를 따르는 다음 리드 viewModel, 세 개의 인터페이스 컨트롤, 상단 부분, 부분적 두 개의 버튼이 +1 및 +3 작업
여기에 사진 설명 삽입
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 엔티티 클래스

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

    public int getScore() {
    
    
        return score;
    }

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

레이아웃 파일 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>

실행 효과는 다음과 같습니다.
여기에 사진 설명 삽입
앱이 백그라운드로 전환 될 때 메모리가 부족할 때 전화가 전력을 절약하기 위해 프로세스를 종료하고 사용자가 전화 구성 (예 : 전화 언어) 또는 앱 설정을 수동으로 변경합니다. 그런 다음 앱을 열면 이전에 계산 된 점수가 0이됩니다. 효과는 다음과 같습니다.

여기에 사진 설명 삽입
이전에는 인터페이스 데이터 캐시가 onSaveInstanceState 메서드에 저장되었고 번들은 onRestoreInstanceState 메서드 또는 onCreate 메서드에서 판단되고 값이 에코되었습니다. viewmodel을 사용하면 훨씬 간단합니다.

MyMainModel 클래스를 추가하여 ViewModel을 상속하고 방금 ScoreModel을 대체합니다. 코드는 다음과 같습니다.

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

    public int getScore() {
    
    
        return score;
    }

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


종속성 추가

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

변경된 MainActivity, 기타 변경되지 않음

/**
 * 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()));
            }
        });
    }

}


작동 효과는 이전과 동일합니다. 이제 시스템 언어를 전환 해보십시오. viewodel이 처리하는 데 도움이 되었기 때문에 인터페이스 데이터가 손실되지 않습니다.

여기에 사진 설명 삽입

이 기록 만 궁금한 점이 있으면 지적 해주세요, 감사합니다

추천

출처blog.csdn.net/nongminkouhao/article/details/114992335