Android : ViewModel_解决textView 横竖屏数据丢失

横竖屏切换  textView  数据丢失

1.导包  

// 使用androidx版本库
    implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0-alpha03'
     // 或者,使用support版本库
    implementation 'android.arch.lifecycle:extensions:1.1.1'

2.写个类 继承 viewModel

import androidx.lifecycle.ViewModel;

public class MyviewModel extends ViewModel {
    public int num =0;
}

3.

package com.example.myviewmodle;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProviders;


public class MainActivity extends AppCompatActivity {
    private Button button;
    private TextView textView;

    private MyviewModel myviewModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myviewModel= ViewModelProviders.of(this).get(MyviewModel.class);

        button = findViewById(R.id.button);
        textView = findViewById(R.id.textView);

        //从新创建时获取一遍值
        textView.setText(String.valueOf(myviewModel.num));



        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myviewModle.num++;
                textView.setText(String.valueOf(myviewModle.num));
            }
        });
    }
}

你可能感兴趣的:(Android,相关,android,笔记)