0

我有一个与数据库链接的应用程序,我需要在按下后退按钮时打开一个菜单,其中包含保存、退出和取消选项。菜单已经创建,它可以工作(与列表视图一起使用),但我不知道如何将它与该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);
    }
}
4

3 回答 3

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;
    }
}
于 2013-10-21T21:02:51.267 回答
1

您只需要像这样覆盖活动的 onBackPressed 方法:

@Override
public void onBackPressed() {
    //Do what you want
}

编辑: doopye 的回答是一个好方法。

您可以像这样为 AlertDialog.Builder 设置自定义视图:

builder.setView('yourListView');
于 2013-10-21T20:58:21.927 回答
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);
}
于 2013-10-21T21:11:40.203 回答