android fragment动态显示隐藏

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private FrameLayout frameLayout;
    private Button btnLogin;
    private Button btnZhuCe;
    private LoginFragment f1;
    private ZhuCeFragment f2;

    @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        frameLayout = (FrameLayout) findViewById(R.id.fl);
        btnLogin = (Button) findViewById(R.id.btn_login);
        btnZhuCe = (Button) findViewById(R.id.btn_zhuce);
        btnLogin.setOnClickListener(this);
        btnZhuCe.setOnClickListener(this);
        initFragment1();
    }
    private void initFragment1(){
        //开启事务,fragment的控制是由事务来实现的
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        //第一种方式(add),初始化fragment并添加到事务中,如果为null就new一个
        if(f1 == null){
            f1 = new LoginFragment();
            transaction.add(R.id.fl, f1);
        }
        //隐藏所有fragment
        hideFragment(transaction);
        //显示需要显示的fragment
        transaction.show(f1);

        //第二种方式(replace),初始化fragment
//        if(f1 == null){
//            f1 = new MyFragment("消息");
//        }
//        transaction.replace(R.id.main_frame_layout, f1);

        //提交事务
        transaction.commit();
    }

    //显示第二个fragment
    private void initFragment2(){
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        if(f2 == null){
            f2 = new ZhuCeFragment();
            transaction.add(R.id.fl,f2);
        }
        hideFragment(transaction);
        transaction.show(f2);

//        if(f2 == null) {
//            f2 = new MyFragment("联系人");
//        }
//        transaction.replace(R.id.main_frame_layout, f2);

        transaction.commit();
    }

    //隐藏所有的fragment
    private void hideFragment(FragmentTransaction transaction){
        if(f1 != null){
            transaction.hide(f1);
        }
        if(f2 != null){
            transaction.hide(f2);
        }

    }


    @Override
    public void onClick(View view) {

            if(view == btnLogin){
                initFragment1();
            }else if(view== btnZhuCe){
                initFragment2();
            }

    }
}

你可能感兴趣的:(android fragment动态显示隐藏)