[英]How to replace parent fragment view with a child fragment's view?
我正在 Android 工作室中尋找一些幫助,當單擊父片段中的視圖時,將父片段的視圖替換為子片段的視圖。 預先感謝您的幫助。
現在我有一個父片段,它是一個聊天列表,還有一個子片段(聊天屏幕),當您單擊聊天屏幕的元素(即按鈕)時會顯示。 聊天列表如下所示:
<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?
例如,有沒有辦法改變這個視圖:
對此:
...單擊聊天列表中的元素(第一個)時?
我正在考慮根據是否加載片段將列表視圖的可見性更改為不可見和可見,但這似乎令人頭疼。
請告訴我你的想法,謝謝!
首先,管理片段的最現代方式是 - 導航組件
根據您的方法 - 您正在使用 fragmentTransaction.add 在 prev 片段頂部添加子fragmentTransaction.add
,您可以使用fragmentTransaction.replace instead
此外,您可能希望將子片段背景設置為純色 - 隱藏前一個片段,如果您使用此方法 - 使子片段根可點擊 - 以防止片段點擊。
我的建議——多花點時間學習 Navigation 組件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.