按下时片段不从菜单项开始

Fragment is not starting from menu item when pressed

我正在尝试从工具栏启动一个片段(工具栏也在一个片段中)但它没有启动,当它在主 activity 中时情况并非如此 activity 它工作正常.

If You Want More Reference of any file or want to see other files please tell me I will upload it

Java 文件

Home_Fragment.java

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);

    MaterialToolbar materialToolbar = view.findViewById(R.id.tool_bar);
            materialToolbar.setOnMenuItemClickListener(toolbarItemClickListener);
return view;
    }
    
    private final MaterialToolbar.OnMenuItemClickListener toolbarItemClickListener =
            (MenuItem item) -> {
                Fragment selectedFragment = null;
                if (item.getItemId() == R.id.search_button) {
                    selectedFragment = new Search_Fragment();
                }
               
                return true;
            };

XML 文件

tool_bar.xml(菜单XML)

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/search_button"
        android:icon="@drawable/ic_baseline_search_24"
        android:title=""
        app:showAsAction="always"
        android:iconTint="@color/white"/>

</menu>

tool_bar.xml

<com.google.android.material.appbar.MaterialToolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/tool_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:background="@color/black"
    app:itemIconSize="29dp"
    app:layout_scrollFlags="scroll|enterAlways"
    app:menu="@menu/tool_bar">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/app"
        android:textColor="@color/white"
        android:textSize="23sp"
        android:textStyle="bold" />

</com.google.android.material.appbar.MaterialToolbar>

您刚刚创建了 Fragment 的新实例,但没有将其添加到 FragmentManager,因此它没有启动。您必须创建 FragmentTransaction 才能启动片段。

片段 selectedFragment = null;

if (item.getItemId() == R.id.search_button) {
    selectedFragment = new Search_Fragment();
    getParentFragmentManager.beginTransaction()
        .replace(R.id.fragment_container, Search_Fragment.class, null) // fragment_container is the ID of the fragment holder
        .setReorderingAllowed(true)
        .commit();
}