java - 我正在尝试从 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;
}
}
如果我做错了什么请纠正我
解决方案
您可以使用 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">
推荐阅读
- javascript - save data with custom keys firebase react native
- css - 如何为项目中的所有 .less 文件添加命名空间?
- vba - 在 Powerpoint 中插入并自动播放音频文件?
- android - Jetifier 后 Android Zendesk SDK v1 Offline Message Fragment 布局无效
- excel - VBA - 基于标识符,在目录中动态打开工作簿并粘贴每个值?
- nlp - 如何在 BERT 的帮助下找到段落的上下文?
- javascript - 如何重置已安装组件中道具更改的状态?
- mysql - 将我的 C 脚本连接到 MySQL 在线数据库时出错
- c# - 如何在 GroupBox 标题旁边显示 ErrorProvider 错误图标?
- nativescript - Nativescript ios 构建失败并出现错误 65