jetpack实例化ViewModel子类,ViewModelProviders弃用
程序员文章站
2022-06-07 16:53:18
...
在build.grade中添加依赖(版本可不一样):
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
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);
}
}