我有一个Android应用程序,我需要在两个标签之间切换。我正在使用碎片。问题是,当我在一个选项卡上的editText框中键入内容并切换到另一个选项卡时,原始的选项卡将重置为默认值。
根据我在不同论坛上找到的答案,我正在保存状态:
@Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, show the tab contents in the
// container view.
Fragment fragment = new TabsSectionFragment();
//fragment.setRetainInstance(true);
Bundle args = new Bundle();
args.putInt(TabsSectionFragment.ARG_SECTION_NUMBER,
tab.getPosition() + 1);
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment).commit();
}
@Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
在onCreateView中,我正在加载几个布局:
public static class TabsSectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public TabsSectionFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
int selectedSection = getArguments().getInt(ARG_SECTION_NUMBER);
switch (selectedSection)
{
case 1:
// load the input layout XML
LayoutInflater factory1 = LayoutInflater.from(getActivity());
View myView1 = factory1.inflate(R.layout.tab1, null);
return myView1;
case 2:
// load the summary layout XML
LayoutInflater factory2 = LayoutInflater.from(getActivity());
View myView2 = factory2.inflate(R.layout.tab2, null);
return myView2;
default:
// Create a new TextView and set its text to the fragment's section
// number argument value.
TextView textView = new TextView(getActivity());
textView.setGravity(Gravity.CENTER);
textView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return textView;
}
}
}
我应该如何使用savedInstanceState来恢复选项卡状态,这样我就不会丢失在切换选项卡之前键入的信息。
我还读到有些人建议隐藏和显示片段而不是保存/重新加载状态。什么是更好的选择。
提前致谢!!
答案 0 :(得分:0)
我会改变你的做法并使用tabhost
private TabHost tabhost;
private View view1;
private View view2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainLayout);
tabhost = (TabHost) findViewById(R.id.tabhostView);
tabhost.setup();
tabhost.getTabWidget().setDividerDrawable(R.drawable.tab_divider);
view1 = getLayoutInflater().inflate(R.layout.view1, null);
view2 = getLayoutInflater().inflate(R.layout.view2, null);
setupTab(view1, "View1");
setupTab(view2, "View2");
//set tab
tabhost.setCurrentTab(getIntent().getExtras().getInt(CURRENT_TAB));
}
然后创建2个方法来设置每个视图,如:
private void buildView1(View view) {
<enter code here>
view.invalidate
}