1
如果我想跟踪一个int值的一个活动/片段,是这种方法不正确:安卓:保持活动/片段状态
在布局XML,具有:
<TextView
android:id="@+id/int_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
在片段的onCreateView
或活动的onCreate
,有下面的代码:
TextView intId = (TextView)getView().findViewById(R.id.int_id);
intId.setText(String.valueOf(<integer_value_to_keep_track_of>));
然后,每当我需要在后面的代码使用int值,做后续访问它ing:
int accessId = Integer.valueOf(((TextView)getView().findViewById(R.id.detail_column_id)).getText().toString());
东西告诉我,这不是保存状态的最好方法。会宣布一个班级成员(例如private int accessId
)并将其分配更好?谢谢!
如果我需要访问''的外onCreateView intId' '?我只在用户在片段中进行选择时才访问它。之前,我有'private int accessId'定义为类成员,并已分配。虽然片段被中断(例如收到电话),但我仍然发现这种方法存在问题。 –
您可以保存'Fragment'的状态,然后在中断后恢复。 – Emmanuel
所以你说的不是使用'TextView',而是定义一个类变量'private int accessId',分配它,并在稍后使用该值?在'FragmentActivity'中,实现'onSaveInstanceState'和'onRestoreInstanceState'? –