我有以下问题。我只在MainActivity中为我的应用程序使用ListView。为了能够执行多个项目选择,我为ListView实现了以下逻辑:
listview.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
@Override
public void onItemCheckedStateChanged(ActionMode actionMode, int i, long l, boolean b) {
Cursor cursor = item_repository.getItemList();
if (listview.getCheckedItemCount() > 0)
actionMode.setSubtitle(listview.getCheckedItemCount() + " item(s) selected");
cursor.moveToPosition(i);
if (b) {
item_ids.add(cursor.getString(0));
listview.getChildAt(i).setBackgroundColor(getResources().getColor(R.color.selected_item_color));
} else {
item_ids.remove(cursor.getString(0));
listview.getChildAt(i).setBackgroundColor(Color.WHITE);
}
}
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
MenuInflater inflater = actionMode.getMenuInflater();
inflater.inflate(R.menu.sel_del_btn, menu);
actionMode.setTitle("Select Item(s)");
return true;
}
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
if (menuItem.getItemId() == R.id.delete_ab_btn) {
AlertDialog.Builder del_builder = new AlertDialog.Builder(MainActivity.this);
View del_view = getLayoutInflater().inflate(R.layout.del_layout, null);
del_builder.setView(del_view);
AlertDialog del_dialog = del_builder.create();
del_dialog.show();
Button yes_btn = del_view.findViewById(R.id.yes_btn);
yes_btn.setOnClickListener((View v) -> {
for (String id : item_ids)
list_repository.deleteData(id);
Toast.makeText(MainActivity.this, "Selected item(s) successfully deleted", Toast.LENGTH_LONG).show();
del_dialog.dismiss();
update();
});
Button no_btn = del_view.findViewById(R.id.no_btn);
no_btn.setOnClickListener((View v) -> {
del_dialog.dismiss();
});
}
if(menuItem.getItemId() == android.R.id.home) {
// How to catch
}
update();
actionMode.finish();
return true;
}
public void onDestroyActionMode(ActionMode actionMode) {
}
});
逻辑有效。但是,当我选择“项目”时,只需单击“后退箭头”或在屏幕上的任意位置,即可取消选择,这些项目将保持选中状态,而不是被取消选择。
正如您在代码中看到的那样,我为所选项目手动设置了不同的颜色。因为,这是我的实现最合适的逻辑。
单击后退箭头以再次手动重置颜色后,我尝试捕获一个事件,但是它不起作用,尤其是在取消选择时无法捕获其事件。
我该如何解决?在此先感谢您,如果我不够清楚,请告诉我,我会再试一次。
后退箭头事件可以通过使用来访问onDestroyActionMode(ActionMode actionMode)
,
即
public void onDestroyActionMode(ActionMode actionMode) {
Toast.makeText(MainActivity.this, "Clicked Back Button", Toast.LENGTH_SHORT).show();
}
希望对您有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句