Android Studio 之 ViewModel

ViewModel is a functional JetPack class library, you can save the state of the control throughout the Activity life cycle, the state will not fail

Such as screen flip, the state can keep, will not fail!

Used in conjunction with LiveData!

Sqlite database operations carried out with the Room

 

 

 

ViewModel new class, right-click on the parent node MainActivity class, creating points java class

Note: Superclass to be selected ViewModel

 

 

1. ViewModel class in a public place of integer variable

 

 


2. Create a MyViewModel instance MainActivity class,

Note: ViewModelProviders this object, in need build.gradle dependencies of the node, add a reference implementation 'androidx.lifecycle: lifecycle-extensions:

 

package com.example.viewmodel1;

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 {

    MyViewModole myViewModole;
    TextView textView;
    Button button1;
    Button button2;

    String TAG = "myTag";

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

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


        = ViewModelProviders.of myViewModole (the this) .get (MyViewModole.class);   // instantiate      
         textView.setText (String.valueOf (myViewModole.numberAnInt)); // initially assigned to it

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                myViewModole.numberAnInt++;
                textView.setText(String.valueOf(myViewModole.numberAnInt));
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                myViewModole.numberAnInt += 2;
                textView.setText(String.valueOf(myViewModole.numberAnInt));
            }
        });
    }
}

  

 

Guess you like

Origin www.cnblogs.com/gfwei/p/11779287.html