我一直在這一整天工作,而且我非常接近,但無法實現這個目標。我有一個按鈕,可以打開一個AlertDialog,其中包含名稱和價格的保存條目。現在,我可以點擊對話框中的一個項目,並自動填寫我的活動中的名稱和價格字段。我想也能夠長時間按一個項目並收到刪除它的選項。這是我第一次嘗試使用Android應用程序,其中很多內容都是從記事本教程中重新使用的。我弄不明白兩件事:請幫我在AlertDialog中設置一個上下文菜單
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();
}
});
}
感謝您的回覆。你有什麼可能指出我正確的方向來創建AlertDialog的自定義子類?謝謝。 – evanl81 2010-11-13 21:55:32
我打算用這個過夜:http://developer.android.com/guide/topics/ui/dialogs.html#CustomDialog – evanl81 2010-11-13 21:57:51
@ evanl81:不,那個樣本不太適合您的需求。你需要創建一個* AlertDialog(或者'Dialog'的自定義子類*,比如http://dtmilano.blogspot.com/2010/01/android-ui-colored-dialogs.html)你可能會發現在你的清單條目中使用一個以對話爲主題的'Activity'('android:theme =「@ android:style/Theme.Dialog」'')更簡單。 – CommonsWare 2010-11-13 22:04:26