所以我现在的问题是,现在我长时间点击ListView中的一个项目,它会调出一个上下文操作栏。传递给onItemLongClick的id是我想在mActionModeCallback的ActionItemClicked()方法中使用的变量。这似乎是一个相当常见的过程,因为如果用户正在编辑项目列表,您将希望在用户单击“编辑”或“删除”操作时以某种方式访问数据库中该行的ID。
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> p, View view, int pos, long id) {
//The id of the row in the database
long variableThatIWantToPassToCallback = id;
mActionMode = getActivity().startActionMode(mActionModeCallback);
view.setSelected(true);
return true;
}
});
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
public boolean onCreateActionMode(ActionMode mode, Menu menu) {}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
//I would like access to the id of the clicked item here, NOT item.getItemId()
}
public void onDestroyActionMode(ActionMode mode) {}
};
答案 0 :(得分:8)
执行此操作的正确方法是在mActionMode.setTag("1")
中拨打onItemCheckedStateChanged
,然后从onActionItemClicked
函数调用mode.getTag();
答案 1 :(得分:1)
通过扩展接口ActionMode.Callback
private interface ActionCallback extends ActionMode.Callback {
public void setClickedView(View view);
}
private ActionCallback mActionModeCallback = new ActionCallback() {
public View mClickedView;
public void setClickedView(View view) {
mClickedView = view;
}
// Called when the action mode is created; startActionMode() was called
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate a menu resource providing context menu items
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
return true;
}
// Called each time the action mode is shown. Always called after onCreateActionMode, but
// may be called multiple times if the mode is invalidated.
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false; // Return false if nothing is done
}
// Called when the user selects a contextual menu item
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item ) {
switch ( item.getItemId() ) {
case R.id.menu_delete:
Log.v( TAG, "#onActionItemClicked ready to delete the item with id: " + mClickedView.getTag() );
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
} // end switch
}
// Called when the user exits the action mode
@Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
};
对于附加OnLongClickListener
的视图,请以这种方式覆盖onLongClick
回调。
@Override
// Called when the user long-clicks on someView
public boolean onLongClick( View view ) {
// proceed only when actionmode is not null
// otherwise overlapping action modes will be
// displayed
if( mActionMode != null ) {
return false;
}
mActionModeCallback.setClickedView(view);
// Start the CAB using the ActionMode.Callback defined above
mActionMode = startActionMode( mActionModeCallback );
view.setSelected(true);
return true;
}