Android循环依赖,需要打开依赖模块的Fragment
创始人
2024-10-12 19:00:49
0

假设我们有两个模块 Module A 和 Module B,其中 Module A 依赖 Module B。如果我们从 Module A 打开一个依赖于 Module B 的 Fragment,就会出现循环依赖的问题。解决这个问题的方法是创建一个接口,Module A 实现该接口并在其中添加一个方法,定义从 Module A 打开依赖的 Fragment;Module B 通过接口回调实现该方法,以此解决循环依赖。

以下是示例代码:

在 Module B 中的 Fragment:

public class FragmentB extends Fragment {

    public interface OnFragmentInteractionListener {
        void openFragmentA();
    }

    private OnFragmentInteractionListener mListener;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    // 在相应事件触发后调用该方法,打开依赖 Module A 的 Fragment
    private void openFragmentA() {
        mListener.openFragmentA();
    }
}

在 Module A 中的 Activity:

public class ActivityA extends AppCompatActivity implements FragmentB.OnFragmentInteractionListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_a);

        // 打开 Module B 的 Fragment
        FragmentB fragment = new FragmentB();
        getSupportFragmentManager().beginTransaction().add(R.id.container, fragment).commit();
    }

    @Override
    public void openFragmentA() {
        FragmentA fragment = new FragmentA();
        getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).addToBackStack(null).commit();
    }
}

在 Module A 中的 Fragment A:

public class FragmentA extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_a, container, false);
        return view;
    }
}

相关内容

热门资讯

透视游戏"hhpok... 1、透视游戏"hhpoker外挂靠谱吗"详细辅助攻略方法(辅助脚本辅助)2、进入游戏-大厅左侧-新手...
透视工具"poker... 透视工具"pokermaster辅助器"详细辅助新版2025教程(游戏安装教程技巧)1、不需要AI权...
透视辅助"德州透视插... 透视辅助"德州透视插件"详细辅助2025教程(辅助脚本透明)准备好在德州透视插件 ia的高塔上攀登,...
透视工具"aapok... 透视工具"aapoker怎么设置抽水"详细辅助大神讲解(可以看底牌透视)1、玩家可以在aapoker...
透视好友房"poke... 透视好友房"pokemmo辅助脚本"详细辅助透明挂教程(插件下载攻略);大神普及一款德州ai内幕,确...
透视模拟器"wepo... 透视模拟器"wepoker免费脚本咨询"详细辅助教你教程(免费钻石透明)是一款可以让一直输的玩家,快...
透视存在"uupok... 透视存在"uupoker有透视吗"详细辅助透明教程(祈福有用透明);亲真的是有正版授权,小编(透视辅...
透视挂"wepoke... 透视挂"wepokerplus透视脚本免费"详细辅助可靠教程(辅助真的假的透视)准备好在wepoke...
透视ai代打"约局吧... 透视ai代打"约局吧开挂神器是真的吗"详细辅助技巧教程(钻石可以看底牌神器)是一款可以让一直输的玩家...
透视美元局"soho... 透视美元局"sohoo poker辅助器"详细辅助我来教教你(有插件神器)是一款可以让一直输的玩家,...