How to implement a custom AlertDialog View

前端 未结 11 881
悲&欢浪女
悲&欢浪女 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:42

    android.R.id.custom was returning null for me. I managed to get this to work in case anybody comes across the same issue,

    AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setTitle("My title")
                .setMessage("Enter password");
    final FrameLayout frameView = new FrameLayout(context);
    builder.setView(frameView);
    
    final AlertDialog alertDialog = builder.create();
    LayoutInflater inflater = alertDialog.getLayoutInflater();
    View dialoglayout = inflater.inflate(R.layout.simple_password, frameView);
    alertDialog.show();
    

    For reference, R.layout.simple_password is :

    <?xml version="1.0" encoding="utf-8"?>
    
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    
    <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/password_edit_view"
            android:inputType="textPassword"/>
    <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/show_password"
            android:id="@+id/show_password_checkbox"
            android:layout_gravity="left|center_vertical"
            android:checked="false"/>
    
    </LinearLayout>
    
    0 讨论(0)
  • 2020-11-22 13:44

    It would make the most sense to do it this way, least amount of code.

    new AlertDialog.Builder(this).builder(this)
            .setTitle("Title")
            .setView(R.id.dialog_view)   //notice this setView was added
            .setCancelable(false)
            .setPositiveButton("Go", new DialogInterface.OnClickListener() {
                @Override 
                public void onClick(DialogInterface dialog, int id) {
                    EditText textBox = (EditText) findViewById(R.id.textbox);
                    doStuff();
                }
            }).show();
    

    For an expanded list of things you can set, start typing .set in Android Studio

    0 讨论(0)
  • 2020-11-22 13:45

    After changing the ID it android.R.id.custom, I needed to add the following to get the View to display:

    ((View) f1.getParent()).setVisibility(View.VISIBLE);
    

    However, this caused the new View to render in a big parent view with no background, breaking the dialog box in two parts (text and buttons, with the new View in between). I finally got the effect that I wanted by inserting my View next to the message:

    LinearLayout f1 = (LinearLayout)findViewById(android.R.id.message).getParent().getParent();
    

    I found this solution by exploring the View tree with View.getParent() and View.getChildAt(int). Not really happy about either, though. None of this is in the Android docs and if they ever change the structure of the AlertDialog, this might break.

    0 讨论(0)
  • 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

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  android:orientation="vertical"
                  android:paddingLeft="20dp"
                  android:paddingRight="20dp"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent">
    
        <EditText
            android:id="@+id/editText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    
    </LinearLayout>
    

    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?
    0 讨论(0)
  • 2020-11-22 13:52

    This worked for me:

    dialog.setView(dialog.getLayoutInflater().inflate(R.layout.custom_dialog_layout, null));
    
    0 讨论(0)
提交回复
热议问题