首页 > 解决方案 > 我正在尝试从 onOptionsItemSelected 方法打开一个片段

问题描述

我正在尝试从活动中调用片段。但不能。这是我尝试过的。

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    if (item.getItemId()==R.id.action_search){
        SearchFragment searchFragment=new SearchFragment();
        getSupportFragmentManager().beginTransaction().add(R.id.container,searchFragment,null).commit();
    }
    return true;
}

还有我的 main_activity.xml

<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/container"
tools:context=".Controllers.MainActivity">

在尝试应用程序确实崩溃后,但它也没有打开我想要的片段。

片段 xml

<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"
android:id="@+id/searchFragment"
tools:context=".SearchFragment">

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerViewSearchFrag"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</androidx.recyclerview.widget.RecyclerView>

而片段java是

public class SearchFragment extends Fragment {

private RecyclerView mRecyclerViewSearch;
private RecyclerViewAdpater mAdpater;

public SearchFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    View view=inflater.inflate(R.layout.fragment_search, container, false);
    mRecyclerViewSearch=view.findViewById(R.id.recyclerViewSearchFrag);
    mRecyclerViewSearch.setLayoutManager(new LinearLayoutManager(getContext()));
    mAdpater=new RecyclerViewAdpater(DataSevices.mChineseColors,getActivity());

    return view;
}

}

如果我做错了什么请纠正我

标签: javaandroidandroid-layoutandroid-fragments

解决方案


您可以使用 Framlayout 而不是 Linear-layout

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent">

推荐阅读