我们的横竖屏布局文件:
竖屏XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Worald!" />
</RelativeLayout>
横屏XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello land!" />
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher" />
</RelativeLayout>
我们的java文件,主要演示saveInstanceState的使用:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
String TAG = "buder";
TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = findViewById(R.id.text);
//方式一:数据恢复,从K-V中获取销毁之前的存储值
if (savedInstanceState != null) {
String test = savedInstanceState.getString("hehe");
Log.e(TAG, "onCreateRestore" + test);
mTextView.setText(test);
}
}
//在pause/stop之间进行界面上的数据存储,到K-V中
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.e(TAG, "onSaveInstanceState");
String change = mTextView.getText().toString();
outState.putString("hehe", change);
}
//方式二:数据恢复,从K-V中获取销毁之前的存储值
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
String test = savedInstanceState.getString("hehe");
Log.e(TAG, "onRestore" + test);
mTextView.setText(test);
}
}
项目地址:https://github.com/buder-cp/base_component_learn/tree/master/instancestatetest