2011-06-09 80 views
0

我有一个名为MyView的自定义视图,它从XML布局扩展其内容。在XML中,我有一个TextView,其ID是“文本”。我的活动中有2个MyViews。所以有2个ID为“text”的视图。这导致Android的onSaveInstanceState实现问题 - 只有一个TextView被保存。如何解决这个问题?我的自定义视图不保存其状态

回答

0

简单的答案是更改您的一个“文本”视图的ID。

+0

如何做到这一点? – fhucho 2011-06-09 12:43:00

+0

那么,你在你的问题中声明你有两个不同的视图,其ID为“text”。您需要将其中一个更改为具有不同的ID。没有看过你的代码来知道你是如何实现的,我不能再比这个更具体。 – 2011-06-09 12:46:00

+0

我有一个从myview.xml加载布局的MyView类。在myview.xml中有一个id =“text”的TextView。在activity.xml中我有2个MyViews。它们中的每一个都会从myview.xml中加载它的内容。所以如果我在myview.xml中修改id,我的MyViews的_both_将会有一个带有新id的TextView。 – fhucho 2011-06-09 12:58:21

0

我有这个问题,我不喜欢改变ID的想法。经过大量的研究,我发现了一个解决方案,覆盖了onAttachedToWindow()方法,并且仅在其内部更改了对象值,而不是在onRestoreInstanceState中进行更改。我希望它有帮助。

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

} 

@Override 
protected void onRestoreInstanceState(Parcelable state) { 
    if (state instanceof Bundle) { 
      bundle = (Bundle) state; 

      state = bundle.getParcelable("instanceState"); 
    } 
    super.onRestoreInstanceState(state); 
} 

@Override 
protected void onAttachedToWindow() { 
    if (bundle != null){ 
     txt_edit.setText(bundle.getString("Text")); 
    } 

    super.onAttachedToWindow(); 
}