Android中经常需要用到view数据的缓存,比如我们希望EditText 在被切到别的界面的时候,输入的数据要仍保持不变。
参考代码:
/* 缓存textview */ public class CPComplexDatePicker extends FrameLayout { private Context mContext; /** * 日期展示 */ private TextView mExpireTxt; /** * 选中的日期 */ private String mSelectedDate; /** * 布局 */ private View mContentView; public CPComplexDatePicker(Context context) { super(context); mContext = context; init(); } public CPComplexDatePicker(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; init(); } /** * 设置日期 * * @param text */ public void setText(String text) { if (mExpireTxt != null) { mExpireTxt.setText(text); } } @SuppressLint("InflateParams") private void init() { mContentView = LayoutInflater.from(mContext).inflate( R.layout.realname_complex_date_picker, (ViewGroup) getRootView()); mExpireTxt = (TextView) mContentView .findViewById(R.id.pid_card_expire_txt); } /** * 保存 */ @Override public Parcelable onSaveInstanceState() { Parcelable parcelable = super.onSaveInstanceState(); SavedState ss = new SavedState(parcelable); ss.mCacheDate = mSelectedDate; return ss; } /** * 恢复 */ @Override public void onRestoreInstanceState(Parcelable state) { SavedState ss = (SavedState) state; mSelectedDate = ss.mCacheDate; // 恢复文本内容 setText(ss.mCacheDate); super.onRestoreInstanceState(ss.getSuperState()); } /** * 数据恢复 * * @author wangmingxian * */ public static class SavedState extends BaseSavedState { /** * 缓存日期 */ String mCacheDate; SavedState(Parcelable superState) { super(superState); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeString(mCacheDate); } private SavedState(Parcel in) { super(in); mCacheDate = in.readString(); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }