jetpack实例化ViewModel子类,ViewModelProviders弃用

在build.grade中添加依赖(版本可不一样):

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

jetpack实例化ViewModel子类,ViewModelProviders弃用_第1张图片
grade之后,在activate或fragment中实例化自定义的ViewModel:
先:import androidx.lifecycle.ViewModelProvider
再:selfViewModel = new ViewModelProvider(this).get(SelfViewModel.class);
完整代码如下:

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;

import com.example.scorebyjava.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {
    SelfViewModel selfViewModel;
    ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        selfViewModel = new ViewModelProvider(this).get(SelfViewModel.class);
        binding.setData(selfViewModel);
        binding.setLifecycleOwner(this);
    }
}

你可能感兴趣的:(Android)