我有一个Activity
,底部有四个按钮,就像标签一样。通过按任意按钮,新的片段将显示在这些按钮上方的FrameLayout中,就像我们在TabActivity中一样。请参阅我的问题here。现在我想我应该找到隐藏和显示这些片段的方法。请告诉我如何在不重新加载片段的情况下显示和隐藏片段。
主要显示隐藏片段的目的是保持其当前状态。在我的一个片段中,我有一个AsyncTask,每当我在片段之间切换时,它再次调用AsynTask。
答案 0 :(得分:2)
//在隐藏时显示片段
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.show(fragment1)
.commit();
//隐藏片段
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.hide(fragment1)
.commit();
答案 1 :(得分:1)
你无法通过像
这样的观点声明4 frameLayout
private FrameLayout fragment1;
private FrameLayout fragment2;
private FrameLayout fragment3;
private FrameLayout fragment4;
和
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment1, Fragment1.newInstance());
ft.replace(R.id.fragment2, Fragment2.newInstance());
ft.replace(R.id.fragment3, Fragment3.newInstance());
ft.replace(R.id.fragment4, Fragment4.newInstance());
ft.commit();
玩可见还是消失了?喜欢
fragment1.setVisibility(View.Visible);
fragment2.setVisibility(View.gone);
fragment3.setVisibility(View.gone);
fragment4.setVisibility(View.gone);
顺便说一句:为我工作 - > public class Activity扩展ActionBarActivity {
private FrameLayout fragment1;
private FrameLayout fragment2;
private Button bt1;
private Button bt2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frg_test_frg);
fragment1 = (FrameLayout) findViewById(R.id.fragment1);
fragment2 = (FrameLayout) findViewById(R.id.fragment2);
bt1 = (Button) findViewById(R.id.button);
bt2 = (Button) findViewById(R.id.button2);
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fragment1.setVisibility(View.VISIBLE);
fragment2.setVisibility(View.GONE);
}
});
bt2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fragment1.setVisibility(View.GONE);
fragment2.setVisibility(View.VISIBLE);
}
});
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment1, new Fragment1());
ft.replace(R.id.fragment2, new Fragment2());
ft.commit();
}