我一整天都在做这件事,我已经很接近了,但就是无法让它发挥作用。我有一个按钮可以拉出一个 AlertDialog,其中填充了已保存的条目,其中包括名称和价格。现在,我可以单击对话框中的某个项目,并让它自动填写我的 Activity 中的名称和价格字段。我还希望能够长按一个项目并收到删除它的选项。这是我第一次尝试 Android 应用程序,其中很多内容都是从记事本教程中重新调整的。有两件事我不明白:
1)我的registerForContextMenu足够/正确吗?
2)我的 onCreateContextMenu 做错了什么?
谢谢。
savedItems.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
cDbHelper.open();
mNotesCursor = cDbHelper.fetchAllSaved();
startManagingCursor(mNotesCursor);
// Create an array of names and corresponding prices from db
String[] from = new String[]{SavedItemsDbAdapter.KEY_NAME, SavedItemsDbAdapter.KEY_PRICE};
// and an array of the fields we want to bind those fields to
int[] to = new int[]{R.id.text1, R.id.text2};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter saved =
new SimpleCursorAdapter(NewEntry.this, R.layout.saved_row, mNotesCursor, from, to);
// Build an AlertDialog to hold this list
AlertDialog.Builder builder = new AlertDialog.Builder(NewEntry.this);
builder.setTitle("Choose from list");
// IS THIS SUFFICIENT TO REGISTER FOR CONTEXT MENU?
registerForContextMenu(v);
builder.setAdapter(saved, new DialogInterface.OnClickListener() {
// When an item from the list is clicked, it automatically populates the name and price fields in activity
@Override
public void onClick(DialogInterface dialog, int item) {
Cursor c = mNotesCursor;
c.moveToPosition(item);
Intent i = new Intent(NewEntry.this, NewEntry.class);
i.putExtra("name", c.getString(
c.getColumnIndexOrThrow(SavedItemsDbAdapter.KEY_NAME)));
i.putExtra("price", c.getString(
c.getColumnIndexOrThrow(SavedItemsDbAdapter.KEY_PRICE)));
startActivityForResult(i, ACTIVITY_AUTO);
finish();
}
// TRYING AND FAILING TO SET UP A CONTEXT MENU - the goal is to be able to long press,
// have a "Delete?" option pop up, which will delete the entry when clicked
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.menu_delete);
}
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
mDbHelper.deleteItem(info.id);
return true;
}
return false;
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
最佳答案
我刚刚发现
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
被召唤,但没有
@Override
public boolean onContextItemSelected(MenuItem item) {
在我的子类 AlertDialog 中:
public class MyAlertDialog extends AlertDialog implements
OnCreateContextMenuListener {
也许这对其他人有用,因为我很确定您已经解决了手头的问题。
关于java - 请帮助我在 AlertDialog 中设置上下文菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4174793/