美文网首页JetPack
Jetpack之ViewModel-SavedState使用教程

Jetpack之ViewModel-SavedState使用教程

作者: wangmf | 来源:发表于2020-05-09 13:26 被阅读0次

1.在Model的Gradle 引入 dataBinding

defaultConfig {
    dataBinding.enabled = true
}

2.添加savedstate依赖库

implementation 'androidx.lifecycle:lifecycle-viewmodel-savedstate:2.3.0-alpha01'

3.创建MyViewModel类并继承ViewModel

private SavedStateHandle handler;

private final String KEY = "key";

public MyViewModel(SavedStateHandle handler) {
    this.handler = handler;
}

public MutableLiveData<Integer> getMutableLiveData() {
    if (!this.handler.contains(KEY)) {
        this.handler.set(KEY, 0);
    }
    return this.handler.getLiveData(KEY);
}

public void add() {
    getMutableLiveData().setValue(getMutableLiveData().getValue() + 1);
}

4.在activity_main.xml文件中使用把控件和数据进行绑定

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="@{()->data.add()}"
        android:text="@string/btn_add"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{String.valueOf(data.getMutableLiveData())}"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.473"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.235" />

</androidx.constraintlayout.widget.ConstraintLayout>

<data>

    <variable
        name="data"
        type="com.example.myapplication.MyViewModel" />

</data>

5.在MainActivity中将MyViewModel 和activity_main.xml进行关联

MyViewModel myViewModel;
ActivityMainBinding binding;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    myViewModel = new ViewModelProvider(this, new SavedStateViewModelFactory(getApplication(), this)).get(MyViewModel.class);
    binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
    binding.setData(myViewModel);
    binding.setLifecycleOwner(this);
}

相关文章

网友评论

    本文标题:Jetpack之ViewModel-SavedState使用教程

    本文链接:https://www.haomeiwen.com/subject/kgxknhtx.html