Jetpack实例化ViewModel子类this报错; ViewModelProviders弃用

​ 在new ViewModelProvider(this).get(MyViewModel.class)时this报错,称无法解析构造函数ViewModelStoreOwner()

Jetpack实例化ViewModel子类this报错; ViewModelProviders弃用_第1张图片

解决方法是在build.grade(app)中添加依赖(版本可不一样)(一般是依赖未添加)

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

gradle之后,就可以在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);
    }
}

你可能感兴趣的:(Jetpack实例化ViewModel子类this报错; ViewModelProviders弃用)