更改“活动"时保持所有值不变 [英] Keep all values intact when changing Activity
问题描述
当我在当前行程标签下输入任何内容并切换到显示结果标签并返回到当前行程标签时,所有条目将恢复为默认值.我该如何预防?
When I enter anything under Current Trip tab and switch to the Display Result tab and come back to the Current Trip tab, all the entries goes back to default. How do I prevent it?
我希望在当前行程下输入或选择的内容保持不变,即使我进入了显示结果标签视图.
I would like anything I enter or select under Current Trip to stay intact even if I go to the Display Result tab view.
我正在使用一个MainActivity,每个选项卡都有两个单独的活动.
I am using one MainActivity which has two separate activities for each tab.
这是Tab片段之一内的内容:
This is what's inside one of the Tab fragment:
package com.test.testing;
public class Trip2 extends Fragment {
EditText nameOfInf;
@Override
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {
final RelativeLayout mFrame2 = (RelativeLayout) inflater.inflate( R.layout.trip, container, false );
final Button btnCalc = (Button) mFrame2.findViewById(R.id.btnCalculate);
nameOfInf = (EditText) mFrame2.findViewById(R.id.etName);
final EditText tollAmount = (EditText) mFrame2.findViewById(R.id.etToll);
btnCalc.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//DO SOMETHING
}
});
return mFrame2;
}
}
我要保存以下值:
nameOfInf = (EditText) mFrame2.findViewById(R.id.etName);
因此,如果我切换到另一个选项卡,它将被保存,返回到选项卡后,该值将保持不变.
So if I switch to another tab this will be saved and upon returning back to the tab the value will stay intact.
如果它可以工作,我该如何实现以下目标:
How do I implement the following if it will work:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("name", nameOfInf.getText());
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
nameOfInf.setText (savedInstanceState.getString("name"));
}
推荐答案
您需要在活动暂停时将状态保存在分发包中,并在活动恢复时恢复该数据.阅读 Android活动生命周期.
You need to save state in a bundle when the activity is paused, and restore that data when the activity is resumed. Read up on the Android activity lifecycle.
这假定您在选项卡控件中嵌入活动.
This assumes you are embedding activities, in a tab control.
这篇关于更改“活动"时保持所有值不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!