The methods onSaveInstanceState()
and onRestoreInstanceState(Parcelable state)
are declared protected in the View
class, while in some of its subclasses, like TextView
or ListView
, they are declared public. To save and restore the state of a ListView
after a configuration change, I can directly use those methods, while I can't for other View
s like ScrollView
. Why those methods are not declared public in the View
class? Am I supposed to call those methods directly from my Activity
/ Fragment
or in some other way? To restore the state of a ScrollView
I can use a custom subclass that change the visibility of those methods to public: is this the way to go?
import android.content.Context;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.widget.ScrollView;
public class MyScrollView extends ScrollView {
public MyScrollView(Context context) {
super(context);
}
public MyScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void onRestoreInstanceState(Parcelable state) {
super.onRestoreInstanceState(state);
}
@Override
public Parcelable onSaveInstanceState() {
return super.onSaveInstanceState();
}
}
- Why those methods are not declared public in the View class?
That is because they are only used to contain View, remember that ScrollView
is a subclass of ViewGroup
which mainly used for storing other views.
From documentation :
A ViewGroup is a special view that can contain other views (called children.)
The view group is the base class for layouts and views containers
- To restore the state of a ScrollView I can use a custom subclass that change the visibility of those methods to public
Yes you can but it is just a container there is nothing special to save and also you can post the position that it will just recompute it again
From documentation :
For example, you will never store your current position on screen because that will be
computed again when a new instance of the view is placed in its view hierarchy.
Some examples of things you may store here: the current cursor position in a text view
(but usually not the text itself since that is stored in a content provider or other
persistent storage), the currently selected item in a list view.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.