activity里面fragment见的跳转

来源:互联网 发布:普通用户 linux 知乎 编辑:程序博客网 时间:2024/05/29 09:21

记得自己之前纠结过一个问题

当一个Activity内有四个fragment时候,怎么某一个fragment中点击某个控件可以跳转到指定的fragment界面内?

解决方法:

在activity内利用FragmentTransaction去管理fragment

一般在activity里都会有一个fragment切换fragment的代码

/**     * 切换Fragment     *     * @param lastIndex 上个显示Fragment的索引     * @param index     需要显示的Fragment的索引     */    private void switchFrament(int lastIndex, int index) {        FragmentTransaction tr = getSupportFragmentManager()                .beginTransaction();        tr.hide(fragments[lastIndex]);        if (!fragments[index].isAdded()) {            tr.add(R.id.fragment_container, fragments[index]);        }        tr.show(fragments[index]).commitAllowingStateLoss();        fragments[index].setUserVisibleHint(true);    }


上述代码中fragments是承载所有fragment的集合

假设我在第四个fragment中 添加一个TextView,点击这个控件跳转到第三个fragment(即从显示第四个fragment转到显示第三个)

正常来说只要调用Activity中的fragment转换的方法

switchFrament(3, 2)


但如果是首页,往往在转换fragment的同时还 需要 对底部按钮进行切换

 public void jumpToTwo() {        if (lastIndex != 2) {            switchFrament(lastIndex, 2);            lastIndex = 2;            if (lastIndex == 0) {                rb1.setChecked(true);            } else if (lastIndex == 1) {                rb2.setChecked(true);            } else if (lastIndex == 2) {                rb3.setChecked(true);            }            rb4.setChecked(false);        }    }


所以我封装了一个方法,只要在第四个fragment中调用((MainActivity)getActivity).jumpToTwo();

rb 是我底部与fragment对应的按钮