首页 > 学院 > 开发设计 > 正文

底部多个按钮切换Fragment,不重新实例化简单方法!

2019-11-09 18:19:14
字体:
来源:转载
供稿:网友

记录下切换fragment不重新实例化的方法:像淘宝 京东都是这样的效果.

PRivate WarnFragment mWarnFragment;         //申明3个fragment  //我的    private MyselfFragment mMyselfFragment;     //预警    private CloudFragment mCloudFragment;       //云//点击事件mMainRbCloud.setOnClickListener(this);        mMainRbWarn.setOnClickListener(this);        mMainRbMine.setOnClickListener(this);//默认选中第一个setTabSelected(0);//点击事件@Override    public void onClick(View v) {        switch (v.getId()) {            case R.id.main_rb_cloud:                setTabSelected(0);                break;            case R.id.main_rb_warn:                               setTabSelected(1);                break;            case R.id.main_rb_mine:                setTabSelected(2);                break;        }    }//显示fragment    private void setTabSelected(int index) {        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();        hideFragments(transaction);	//先隐藏所有的fragment        switch (index) {            case 0:                if(mCloudFragment == null) {                    mCloudFragment = new CloudFragment();                    transaction.add(R.id.main_fr_content,mCloudFragment);                } else {                    transaction.show(mCloudFragment);                }                break;            case 1:                if(mWarnFragment == null) {                    mWarnFragment = new WarnFragment();                    transaction.add(R.id.main_fr_content,mWarnFragment);                } else {                    transaction.show(mWarnFragment);                }                break;            case 2:                if(mMyselfFragment == null) {                    mMyselfFragment = new MyselfFragment();                    transaction.add(R.id.main_fr_content,mMyselfFragment);                } else {                    transaction.show(mMyselfFragment);                }                break;        }        transaction.commit();    }    //隐藏所有fragment防止显示多个    private void hideFragments(FragmentTransaction transaction) {        if(mCloudFragment!=null) {            transaction.hide(mCloudFragment);        }        if(mWarnFragment!=null) {            transaction.hide(mWarnFragment);        }        if(mMyselfFragment!=null) {            transaction.hide(mMyselfFragment);        }    }

上面是核心代码, 具体要切换按钮的状态,自己随意写.


上一篇:热更新hot update大纲

下一篇:粒子动画

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表