一、说在前面
昨天 | 对界面显示和逻辑结构进行完善 |
今天 |
1、添加菜单(查询、清除所有等) 2、使用滑动删除 |
问题 |
1、在做查询时获取SearchView时引 入包错误经过长时间的尝试后才修正 2、滑动删除的撤销问题。 |
二、菜单设计
1、创建菜单资源
2、添加两个MenuItem 和一个搜索标志
3、将菜单设置在AccountRecordFragment 的界面上,并关联数据库
@Override public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.show_menu,menu); SearchView searchView = (SearchView) menu.findItem(R.id.app_bar_search).getActionView(); searchView.setMaxWidth(1000); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { String type = newText.trim(); findAccountRecord.removeObservers(requireActivity()); findAccountRecord = accountRecordViewModel.getAcountRecordByType(type); findAccountRecord.observe(requireActivity(), new Observer<List<AccountRecord>>() { @Override public void onChanged(List<AccountRecord> accountRecords) { allAccountRecord = accountRecords; myAdpter.setAllAccountRecords(accountRecords); myAdpter.notifyDataSetChanged(); } }); return true; } }); }
4、查询数据库的相关修改
1)dao层
@Query("SELECT * From ACCOUNTRECORD WHERE cost_type LIKE :type ORDER BY ID DESC")
LiveData<List<AccountRecord>> getAccountRecordLiveByType (String type);
2)“工厂”
public LiveData<List<AccountRecord>> getAcountRecordByType(String type) { return accountRecordDao.getAccountRecordLiveByType("%"+type+"%");//实现模糊查询 }
3)ViewModel
public LiveData<List<AccountRecord>> getAcountRecordByType(String type) { return accountRecordRepository.getAcountRecordByType(type); }
4、清空所有账单的设置(“简陋版”)
@Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()){ case R.id.clear: AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity()); builder.setTitle("清空账单"); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { accountRecordViewModel.deleteAllAccountRecord(); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.create(); builder.show(); break; } return super.onOptionsItemSelected(item); }
5、滑动删除
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.START | ItemTouchHelper.END) { @Override public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) { return false; } @Override public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) { AccountRecord accountRecord = allAccountRecord.get(viewHolder.getLayoutPosition()); accountRecordViewModel.deleteAccountRecord(accountRecord); } }).attachToRecyclerView(recyclerView);
三、运行测试