将菜单按钮更改为普通按钮

时间:2016-09-20 05:42:38

标签: java android

            case R.id.Delete_Contact:

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(R.string.deleteContact)
                    .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            mydb.deleteContact(id_To_Update);
                            Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                            startActivity(intent);
                        }
                    })
                    .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // User cancelled the dialog
                        }
                    });
            AlertDialog d = builder.create();
            d.setTitle("Are you sure");
            d.show();

            return true;
        default:
            return super.onOptionsItemSelected(item);

如何在按钮点击事件中使用它?这在单击菜单按钮

时有效

1 个答案:

答案 0 :(得分:2)

//初始化按钮

//将Click Listener设置为如下所示

button.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
            //Perform Some Action
            //common method to be called
            deleteConfirmation();
});

public void deleteConfirmation(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.deleteContact)
                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        mydb.deleteContact(id_To_Update);
                        Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(intent);
                    }
                })
                .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // User cancelled the dialog
                    }
                });
        AlertDialog d = builder.create();
        d.setTitle("Are you sure");
        d.show();

      }
   });

}
  

您应该使用通用方法,因为您希望多次执行相同的代码。这只是一个建议