2013-10-04 111 views
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)并将其分配更好?谢谢!

回答

0

通常情况下,如果你是里面onCreateView()你得到的View s表示是FragmentView层次结构的一部分,只有当你膨胀布局曾经的参考。当您致电infalter.inflate()时,返回一个View实例;层次结构的父级。您可以使用该ViewfindViewById()获取TextView的参考。

例如:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle SavedInstanceState) {   // TODO Auto-generated method stub  

View view = (View) inflater.inflate(R.layout.me_layout, container,false);  
TextView intId = (TextView)view.findViewById(R.id.int_id);    
return view;  
} 

然后,一旦你得到TextView参考,你可以简单地做

String text = intId.getText().toString(); 

onCreateView();

+0

如果我需要访问''的外onCreateView intId' '?我只在用户在片段中进行选择时才访问它。之前,我有'private int accessId'定义为类成员,并已分配。虽然片段被中断(例如收到电话),但我仍然发现这种方法存在问题。 –

+0

您可以保存'Fragment'的状态,然后在中断后恢复。 – Emmanuel

+0

所以你说的不是使用'TextView',而是定义一个类变量'private int accessId',分配它,并在稍后使用该值?在'FragmentActivity'中,实现'onSaveInstanceState'和'onRestoreInstanceState'? –