activity展示点击按钮改变数字,activity销毁重建时数字显示改变之后的
核心是状态保存到这个方法里面
@Override
public void onSaveInstanceState(@NonNull final Bundle outState) {
Log.e("wy","run: "+ "onSaveInstanceState");
super.onSaveInstanceState(outState);
outState.putInt("myInt",i);
}
全代码
package com.dongnaoedu.jetpackstudy;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
public class ViewModelActivity extends AppCompatActivity {
private TextView mTextView;
int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_model);
mTextView = (TextView) findViewById(R.id.textView);
if(savedInstanceState!=null){
i=savedInstanceState.getInt("myInt");
mTextView.setText(i+"");
Log.e("wy","run: "+ i);
}
}
public void plus(View view) {
i++;
mTextView.setText(i+"");
}
@Override
public void onSaveInstanceState(@NonNull final Bundle outState) {
Log.e("wy","run: "+ "onSaveInstanceState");
super.onSaveInstanceState(outState);
outState.putInt("myInt",i);
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".ViewModelActivity">
<TextView
android:id="@+id/textView"
android:layout_width="242dp"
android:layout_height="0dp"
android:layout_marginTop="209dp"
android:layout_marginBottom="243dp"
android:text="TextView"
app:layout_constraintBottom_toTopOf="@+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.603"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="MissingConstraints" />
<Button
android:id="@+id/button"
android:layout_width="207dp"
android:layout_height="0dp"
android:layout_marginBottom="76dp"
android:onClick="plus"
android:text="+"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/textView"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
|