> filteredWords; //过滤后的词汇public WordsFragment() {// Required empty public constructorsetHasOptionsMenu(true);}@Overridepublic void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {super.onCreateOptionsMenu(menu, inflater);inflater.inflate(R.menu.main_menu,menu);SearchView searchView = (SearchView) menu.findItem(R.id.app_bar_search).getActionView();//获取搜索栏的引用searchView.setMaxWidth(1000); //设置搜索栏宽度searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {@Overridepublic boolean onQueryTextSubmit(String query) { //确定提交相关return false;}@Overridepublic boolean onQueryTextChange(String newText) { //内容改变//制作模糊匹配查询String pattern = newText.trim();//避免两次观察的碰撞,先移除之前的观察filteredWords.removeObservers(requireActivity());//不写这句会报错//根据筛选条件获取新的模糊查询添加观察filteredWords = wordViewModel.findWordsWithPattern(pattern);filteredWords.observe(requireActivity(), new Observer
>() {@Overridepublic void onChanged(List
>() {...}}
至此搜索筛选功能完成:
制作清空数据功能和切换布局功能
菜单栏中的选项点击事件的实现在d()中
复写该方法:
@Overridepublic boolean onOptionsItemSelected(@NonNull MenuItem item) {//菜单栏的可选项点击事件的实现(本次为清空数据和切换视图)//多个菜单分类处理switch (item.getItemId()) {case R.id.clearData://选中清空数据时弹出确认对话框AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());builder.setTitle("清空数据");builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {wordViewModel.clearWords();//确定时才从ViewModel中清空数据}});builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {//取消时不做处理即可}});builder.create();builder.show();break;case R.id.switchViewType://选中切换视图时//创建用户偏好设置SharedPreferences保存切换的视图(不设置会在切换视图做添加数据操作的时候回归普通视图)SharedPreferences sharedPreferences = requireActivity().getSharedPreferences(VIEW_TYPE_SHP, Context.MODE_PRIVATE);boolean viewType = sharedPreferences.getBoolean(IS_USING_CARDVIEW,false);SharedPreferences.Editor editor = sharedPreferences.edit();if (viewType) {//当前使用的时卡片布局recyclerView.setAdapter(myAdapter1); //改变为普通布局editor.putBoolean(IS_USING_CARDVIEW,false); //将用户偏好设置改变为false} else {recyclerView.setAdapter(myAdapter2);editor.putBoolean(IS_USING_CARDVIEW,true);}editor.apply(); //用户偏好设置存储}return super.onOptionsItemSelected(item);}
并在填充数据后通过用户偏好设置保持原本界面布局(包括填充数据提交和重新进入界面)
@Overridepublic void onActivityCreated(@Nullable Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);...//读取用户偏好设置SharedPreferences sharedPreferences = requireActivity().getSharedPreferences(VIEW_TYPE_SHP, Context.MODE_PRIVATE);boolean viewType = sharedPreferences.getBoolean(IS_USING_CARDVIEW,false);if (viewType) { //用户偏好卡片则设为卡片布局recyclerView.setAdapter(myAdapter2);} else {recyclerView.setAdapter(myAdapter1);}...}
- 民间传说死后必喝的孟婆汤的制作原料揭秘
- 数千精锐清军搞定不了几百沙俄流民,土耳其却能和他单挑
- 佟国维和康熙有何关系?历史上佟国维的结局如何
- 李悝变法是在哪国推行的?他和吴起哪个变法更早
- 华为p50pro麒麟版和骁龙版区别
- s7和s8的区别
- originos和鸿蒙系统差距
- pro max和pro的区别
- pro和pro max有什么区别
- xs和13对比