How to implement a custom AlertDialog View

前端 未结 11 985
悲&欢浪女
悲&欢浪女 2020-11-22 13:18

In the Android docs on AlertDialog, it gives the following instruction and example for setting a custom view in an AlertDialog:

If you want to display a
11条回答
  •  误落风尘
    2020-11-22 13:48

    Custom AlertDialog

    This full example includes passing data back to the Activity.

    Create a custom layout

    A layout with an EditText is used for this simple example, but you can replace it with anything you like.

    custom_layout.xml

    
    
    
        
    
    
    

    Use the dialog in code

    The key parts are

    • using setView to assign the custom layout to the AlertDialog.Builder
    • sending any data back to the activity when a dialog button is clicked.

    This is the full code from the example project shown in the image above:

    MainActivity.java

    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        public void showAlertDialogButtonClicked(View view) {
    
            // create an alert builder
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Name");
    
            // set the custom layout
            final View customLayout = getLayoutInflater().inflate(R.layout.custom_layout, null);
            builder.setView(customLayout);
    
            // add a button
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // send data from the AlertDialog to the Activity
                    EditText editText = customLayout.findViewById(R.id.editText);
                    sendDialogDataToActivity(editText.getText().toString());
                }
            });
    
            // create and show the alert dialog
            AlertDialog dialog = builder.create();
            dialog.show();
        }
    
        // do something with the data coming from the AlertDialog
        private void sendDialogDataToActivity(String data) {
            Toast.makeText(this, data, Toast.LENGTH_SHORT).show();
        }
    }
    

    Notes

    • If you find yourself using this in multiple places, then consider making a DialogFragment subclass as is described in the documentation.

    See also

    • Android Alert Dialog with one, two, and three buttons
    • How can I display a list view in an Android Alert Dialog?

提交回复
热议问题