ViewModel在Android Studio 新版本中初始化的方法

核心初始化语句:

​
myViewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(MyViewModel.class);

​

例子项目:简易篮球计分器

实现如下:

ViewModel在Android Studio 新版本中初始化的方法_第1张图片

实现步骤:

1.创建一个java类,继承ViewModel,并将number声明为全局变量。

MyViewModel.java

package com.example.viewmodeltest;

import android.arch.lifecycle.ViewModel;

public class MyViewModel extends ViewModel {
    public int number = 0;
}

2.进行UI界面设置,将ViewModel初始化,用以保存数据。

MainActivity.java

package com.example.viewmodeltest;

import android.arch.lifecycle.ViewModelProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    MyViewModel myViewModel;
    TextView textView;
    Button button1, button2, button3;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myViewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(MyViewModel.class);

        textView = findViewById(R.id.textView);
        textView.setText(String.valueOf(myViewModel.number));

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

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myViewModel.number++;
                textView.setText(String.valueOf(myViewModel.number));
            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myViewModel.number += 2;
                textView.setText(String.valueOf(myViewModel.number));
            }
        });

        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myViewModel.number += 3;
                textView.setText(String.valueOf(myViewModel.number));
            }
        });

    }
}

其他:

activity_main.xml




    

    

strings.xml


    ViewModelTest
    Welcome
    +1
    +2
    +3

AndroidManifest.xml




    
        
            
                

                
            
        
    

你可能感兴趣的:(Android,android,studio,android,android-studio)