how to show hide a fragment?

守給你的承諾、 提交于 2019-12-08 08:03:55

问题


I have a Activity with four buttons at the bottom like tabs. By pressing any button a new Fragment is displayed in the FrameLayout above these buttons like we do in TabActivity. See My Problem here .Now i think i should find a way to hide and show those fragments. Kindly tell me how can i show and hide a fragment without reloading it again.

Main Purpose of showing hiding a fragment is to maintain its current state. In one of my fragment i have an AsyncTask whenever i switch between fragment it call that AsynTask again.


回答1:


// to show fragment when it is hidden

FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
          .show(fragment1)
          .commit();

// to hide fragment

FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
          .hide(fragment1)
          .commit();



回答2:


you can't pass by some view like

declare 4 frameLayout

private FrameLayout fragment1;
private FrameLayout fragment2;
private FrameLayout fragment3;
private FrameLayout fragment4;

and

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();

and play with visible or gone ? like

fragment1.setVisibility(View.Visible);
fragment2.setVisibility(View.gone);
fragment3.setVisibility(View.gone);
fragment4.setVisibility(View.gone);

and by the way : works for me -> public class Activity extends 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();
}


来源:https://stackoverflow.com/questions/24779275/how-to-show-hide-a-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!