How do I display an alert dialog on Android?

后端 未结 30 3057
清歌不尽
清歌不尽 2020-11-22 03:02

I want to display a dialog/popup window with a message to the user that shows \"Are you sure you want to delete this entry?\" with one button that says \'Delete\'. When

30条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 03:40

    You can create the dialog box using AlertDialog.Builder

    Try this:

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Are you sure you want to delete this entry?");
    
            builder.setPositiveButton("Yes, please", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //perform any action
                    Toast.makeText(getApplicationContext(), "Yes clicked", Toast.LENGTH_SHORT).show();
                }
            });
    
            builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //perform any action
                    Toast.makeText(getApplicationContext(), "No clicked", Toast.LENGTH_SHORT).show();
                }
            });
    
            //creating alert dialog
            AlertDialog alertDialog = builder.create();
            alertDialog.show();
    

    To change the color of the positive & negative buttons of Alert dialog you can write the below two lines after alertDialog.show();

    alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.colorPrimary));
    alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.colorPrimaryDark));
    

提交回复
热议问题