radiogroup + fragment实现页面切换

Activity布局





    
    

    


        

        

        

        

    



Activity主要逻辑处理

    private Fragment[] mFragments;
    private int mIndex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_radio_group);
        ButterKnife.bind(this);
        initFragment();
    }

    private void initFragment() {
        //首页
        HomeFragment homeFragment = new HomeFragment();
        //购物车
        ShopcartFragment shopcartFragment = new ShopcartFragment();

        //消息
        MessageFragment messageFragment = new MessageFragment();
        //个人中心

        MineFragment mineFragment = new MineFragment();

        //添加到数组
        mFragments = new Fragment[]{homeFragment, shopcartFragment, messageFragment, mineFragment};

        //开启事务
        FragmentTransaction ft =
                getSupportFragmentManager().beginTransaction();

        //添加首页
        ft.add(R.id.content, homeFragment).commit();

        //默认设置为第0个
        setIndexSelected(0);
    }

    private void setIndexSelected(int index) {

        if (mIndex == index) {
            return;
        }
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();

        //隐藏
        ft.hide(mFragments[mIndex]);
        //判断是否添加
        if (!mFragments[index].isAdded()) {
            ft.add(R.id.content, mFragments[index]).show(mFragments[index]);
        } else {
            ft.show(mFragments[index]);
        }

        ft.commit();
        //再次赋值
        mIndex = index;

    }

    @OnClick({R.id.rbHome, R.id.rbShop, R.id.rbMessage, R.id.rbMine, R.id.rgTools})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rbHome:
                setIndexSelected(0);
                break;
            case R.id.rbShop:
                setIndexSelected(1);
                break;
            case R.id.rbMessage:
                setIndexSelected(2);
                break;
            case R.id.rbMine:
                setIndexSelected(3);
                break;
        }
    }

借鉴
https://www.cnblogs.com/liunanjava/p/5814873.html

你可能感兴趣的:(radiogroup + fragment实现页面切换)