Reputation: 3
I have an application linked with a DB, for which I need to open a menu with options of save, exit and cancel when the back button is pressed. The menu is already created, and it works (is used with a listview), but I don't know how to use it with the onbackpressed
method. Any suggestion?
first:
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);
}
});
then:
@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);
}
finally:
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);
}
}
Upvotes: 0
Views: 1613
Reputation: 1029
Try use dialog instead menu .
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;
}
}
Upvotes: 2
Reputation: 8961
You just need to override the onBackPressed method of your activity like this:
@Override
public void onBackPressed() {
//Do what you want
}
Edit: the dooplaye's answer is a good way.
You can set a custom View to the AlertDialog.Builder like this:
builder.setView('yourListView');
Upvotes: 1
Reputation: 85
@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);
}
Upvotes: 0