我有一个与数据库链接的应用程序,我需要在按下后退按钮时打开一个菜单,其中包含save,exit和cancel选项。菜单已经创建,它可以工作(与listview一起使用),但我不知道如何将它与onbackpressed
方法一起使用。有什么建议吗?
第一
registerForContextMenu(listview);
listview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
openContextMenu(listview);
}
});
然后:
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle(R.string.MenuSospechosoQuestion);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_borrar_sospechoso, menu);
}
最后:
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.sospBorrar:
conex = new Conexion(this);
conex.conectar();
conex.actualizar("DELETE FROM SOSPECHOSOS WHERE ID_SOSPECHOSO = " + (ids.get(pos)));
ids.remove(pos);
names.remove(pos);
llenarLista();
conex.desconectar();
return true;
case R.id.sosEditar:
intent = new Intent(DenunciaMenuSuspect.this, Suspect.class);
intent.putExtra("toUpdate", true);
intent.putExtra("id", String.valueOf(ids.get(pos)));
startActivityForResult(intent, 1);
return true;
case R.id.cancelar:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
答案 0 :(得分:2)
尝试使用对话框而不是菜单。
private AlertDialog dialog;
@Override
public void onBackPressed()
{
if(dialog == null)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getBaseContext());
builder.setPositiveButton("save",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//save your data
}
});
builder.setNegativeButton("exit",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setTitle("Are you sure?");
dialog = builder.create();
dialog.show();
}
else
{
super.onBackPressed(); // or dialog.dismiss();
dialog = null;
}
}
答案 1 :(得分:1)
您只需要覆盖活动的onBackPressed方法,如下所示:
@Override
public void onBackPressed() {
//Do what you want
}
编辑: dooplaye的答案是一个好方法。
您可以将自定义视图设置为AlertDialog.Builder,如下所示:
builder.setView('yourListView');
答案 2 :(得分:0)
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK);
this.getWindow().openPanel(Window.FEATURE_OPTIONS_PANEL, event);
}