如何用子片段视图替换父片段视图?

我在Android Studio中寻求一些帮助,方法是单击父片段中的视图时,用子片段的视图替换父片段的视图。预先感谢您的帮助。

现在,我有一个父片段,它是一个聊天列表,以及一个子片段(聊天屏幕),当您单击聊天屏幕的某个元素(即一个按钮)时,该子片段就会出现。聊天列表如下所示:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.myapplication.ChatListFragment">

    <!-- Empty Container for Fragment to Live in -->
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ListView
        android:id="@+id/chatListView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/moonstone">
    </ListView>

</FrameLayout>

如何用子片段视图替换父片段视图?

我为chatListView设置了onClicklistener,如下所示:

_chatListView.setOnItemClicklistener(new AdapterView.OnItemClicklistener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView,View view,int i,long l) {


                String chatName = _chatListAdapter.getItem(i).getchatTitle();

                openChatScreen(chatName);
            }
        });

openChatScreenWindow()看起来像这样:

private void openChatScreen(String chatName)
    {
        _fragmentManager = getchildFragmentManager();

        Log.i(CHAT_LIST_TAG,"starting chat screen fragment");

        FragmentTransaction fragmentTransaction = _fragmentManager.beginTransaction();

        ChatScreenFragment chatScreenFragment = ChatScreenFragment.newInstance(chatName);
        fragmentTransaction.add(R.id.fragment_container,chatScreenFragment);
        fragmentTransaction.addToBackStack(GlobalConstants.OPEN_CHAT_WINDOW_FRAGMENT_STRING + chatName);

        fragmentTransaction.commit();
    }

但是,当我运行这段代码时,子片段被遮盖了,因为框架布局(片段在其中显示的视图)和chatListView的宽度和高度都设置为match_parent(我认为通过将聊天列表的高度和宽度测试为200dp,我可以看到它后面的子片段。

是否有一种简单的方法来获取片段,以便在每次加载chatListView时替换它?

例如,有一种方法可以更改此视图:

如何用子片段视图替换父片段视图?

对此:

如何用子片段视图替换父片段视图?

...当单击聊天列表(第一个)中的元素时?

我当时正在考虑根据片段是否已加载将列表视图的可见性更改为不可见和可见,但这似乎让人头疼。

请让我知道您的想法,谢谢!

mingdou 回答:如何用子片段视图替换父片段视图?

最现代的片段管理方法是-Navigation component

根据您的方法-您使用fragmentTransaction.add在上一个片段的顶部添加子片段,可以使用fragmentTransaction.replace instead

此外,您可能希望将子片段背景设置为纯色-如果使用此方法,则隐藏前一个片段-使子片段的根成为可点击的-防止片段点击。

我的建议-花更多时间学习导航组件

本文链接:https://www.f2er.com/3166475.html

大家都在问