(Android) Custom view orientation change – restore state.

By | July 15, 2014

Here’s one pretty simple way to get your custom view to restore its current state after an orientation change:
You can of course put any values in there, for example if you need to restore fields.

(quickly plotted code. Haven’t run it, but it should work)

@Override
protected Parcelable onSaveInstanceState() {
	Bundle bundle = new Bundle();
	bundle.putParcelable("instanceState", super.onSaveInstanceState());
	bundle.putString("myString", myEditText.getText().toString());
	return bundle;
}

@Override
protected void onRestoreInstanceState(Parcelable state) {
	if (state instanceof Bundle) {
		Bundle bundle = (Bundle) state;
		myEditText.setText(bundle.getString("myString"));
		state = bundle.getParcelable("instanceState");
	}
	super.onRestoreInstanceState(state);
}

Leave a Reply

Your email address will not be published. Required fields are marked *