Add a positive button to the dialog

I have a very simple user dialog and I donโ€™t want to add a positive button without modifying the XML file, just as you would with AlertDialog, but I donโ€™t know if this is possible. This is the code:

final Dialog dialog = new Dialog(MyActivity.this); dialog.requestWindowFeature(Window.FEATURE_LEFT_ICON); dialog.setContentView(R.layout.dialog); dialog.setTitle("Settings"); dialog.show(); 
+6
source share
3 answers

You must use the builder.

 LayoutInflater inflater = LayoutInflater.from(this); View dialog_layout = inflater.inflate(R.layout.dialog,(ViewGroup) findViewById(R.id.dialog_root_layout)); AlertDialog.Builder db = new AlertDialog.Builder(MyActivity.this); db.setView(dialog_layout); db.setTitle("settings"); db.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); AlertDialog dialog = db.show(); 
+11
source

You can use the AlertDialog.Builder class:

http://developer.android.com/reference/android/app/AlertDialog.Builder.html

Create a new instance using AlertDialog.Builder myAlertDialogBuilder = new AlertDialog.Builder(context) . Then use methods such as setTitle() and setView() to customize it. This class also has button customization methods. setPositiveButton(String, DialogInterface.OnClickListener) to customize the buttons. Finally, use AlertDialog myAlertDialog = myAlertDialogBuilder.create() to get your instance of AlertDialog, which you can then configure using methods like setCancelable() .

Edit: Also from the docs: http://developer.android.com/guide/topics/ui/dialogs.html

"The Dialog class is the base class for creating dialogs. However, you usually should not instantiate the dialog box directly. Instead, you should use one of ... subclasses

If you really don't want to use AlertDialog, it is probably best to extend the Dialog class rather than using it as it is.

+2
source

You can also use this function.

 public void showMessage(String title,String message) { AlertDialog.Builder builder=new AlertDialog.Builder(this); builder.setCancelable(true); builder.setTitle(title); builder.setMessage(message); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); builder.show(); } 
+1
source

Source: https://habr.com/ru/post/916409/


All Articles