JetPack(二)ViewModel小试牛刀,Context都没弄明白凭什么拿高薪
作者:互联网
activity_main.xml(通过ConstraintLayout拖拽实现的)
<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android=“http://schemas.android.com/apk/res/android”
xmlns:app=“http://schemas.android.com/apk/res-auto”
xmlns:tools=“http://schemas.android.com/tools”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“Hello World!”
android:textSize=“30sp”
app:layout_constraintBottom_toBottomOf=“parent”
app:layout_constraintEnd_toEndOf=“parent”
app:layout_constraintHorizontal_bias=“0.498”
app:layout_constraintLeft_toLeftOf=“parent”
app:layout_constraintRight_toRightOf=“parent”
app:layout_constraintStart_toStartOf=“parent”
app:layout_constraintTop_toTopOf=“parent”
app:layout_constraintVertical_bias=“0.273”
tools:text=“100” />
<Button
android:id="@+id/button"
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text="+1"
android:textSize=“30sp”
app:layout_constraintBottom_toBottomOf=“parent”
app:layout_constraintEnd_toEndOf=“parent”
app:layout_constraintHorizontal_bias=“0.498”
app:layout_constraintStart_toStartOf=“parent”
app:layout_constraintTop_toTopOf=“parent”
app:layout_constraintVertical_bias=“0.521” />
</android.support.constraint.ConstraintLayout>
My
ViewModel (这里只定义一个简单的变量number)
public class MyViewModel extends ViewModel {
public int number = 0;
}
Activity (先绑定ViewModel,然后拿到number变量的值进行监听)
public class MainActivity extends AppCompatActivity {
MyViewModel myViewModel;
TextView textView;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 绑定ViewModel
myViewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(MyViewModel.class);
textView = findViewById(R.id.textView);
// Activity重新创建时保存number值
textView.setText(String.valueOf(myViewModel.number));
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myViewModel.number++;
textView.setText(String.valueOf(myViewModel.number));
}
});
}
}
上图是官网给的生命周期图,我们可以知道ViewModel存在于Activity各种生命周期。这样我们就不用担心Activity被destory、重新create时、或者旋转时,数据被销毁。比如上面的demo,旋转屏幕时,ViewModel不会重新创建,我们可以直接获取number的值。
g.csdnimg.cn/20201118165146219.png)
上图是官网给的生命周期图,我们可以知道ViewModel存在于Activity各种生命周期。这样我们就不用担心Activity被destory、重新create时、或者旋转时,数据被销毁。比如上面的demo,旋转屏幕时,ViewModel不会重新创建,我们可以直接获取number的值。
标签:layout,parent,JetPack,app,ViewModel,number,android,小试牛刀 来源: https://blog.csdn.net/m0_66264655/article/details/122652478