方法onSaveInstanceState()
和onRestoreInstanceState(Parcelable state)
在View
类中声明受保护,而在某些子类中,如TextView
或ListView
,它们是公开宣布。要在配置更改后保存并恢复ListView
的状态,我可以直接使用这些方法,而我不能用View
之类的其他ScrollView
。为什么这些方法在View
类中没有公开?我应该直接从我的Activity
/ Fragment
或其他方式调用这些方法吗?要恢复ScrollView
的状态,我可以使用自定义子类将这些方法的可见性更改为public:这是要走的路吗?
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();
}
}
答案 0 :(得分:1)
- Why those methods are not declared public in the View class?
这是因为它们仅用于包含View,请记住ScrollView
是ViewGroup
的子类,主要用于存储其他视图。
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
是的,你可以,但它只是一个容器,没有什么特别的保存,你也可以发布它只会重新计算它的位置
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.