我正在尝试从onOptionsItemSelected方法中打开一个片段

问题描述 投票:0回答:1

我正在尝试从活动中调用片段。但是无法。这就是我尝试过的。

@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>

而Fragment 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;
}

}*如果我做错了,请纠正我**

java android android-studio android-layout android-fragments
1个回答
0
投票

您可以使用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">
© www.soinside.com 2019 - 2024. All rights reserved.