Search code examples
androidandroid-layoutandroid-edittextandroid-alertdialogandroid-checkbox

How to design dialog to have Checkboxes and one EditText box?


I'm trying to design the dialog xml file. It's a bit hard to follow the Material Design guidelines. Basically I want the dialog window to allow users to multi-check the checkboxes and on the bottom to have an option to add custom option (one EditText). For example:

Choose the options

[x] Option1
[] Option2
[x] Option3
[] Option4

Add custom options:
__________

       [Cancel] [Ok]

The code I have:

public void onClick(View view) {
    AlertDialog.Builder mBuilder = new AlertDialog.Builder(AddData.this);
    View mView = getLayoutInflater().inflate(R.layout.dialog_adding_data,null);
    // More code here
    mBuilder.show();
}

As I understand I'm using a custom dialog layout. But in the material design guidelines I didn't see an option to do something like that. Also I'm not sure how to to design the dialog_adding_data file. How can I design the dialog_adding_data so it will follow the material design guidelines and have the same functionality?


Solution

  • To achieve your UI requirements, you need to set a custom view to your dialog. The key point here is to use the following:

    mBuilder.setView(mView);
    

    If you are not using view/data binding, when referencing the views, make sure to use mView.findViewById and not findViewById like the following:

    EditText editText = mView.findViewById(R.id.edit_text);
    // Add your code logic, etc.
    

    Concerning dialog_adding_data.xml that you have created, it will simply be like any other layout. Its hierarchy, depending on your exact needs, may look something like this:

    <ScrollView>
    
        <LinearLayout>
    
            <CheckBox />
    
            <CheckBox />
    
            <!-- This one controls the EditText below. -->
            <CheckBox android:text="Add custom options" />
    
            <EditText />
    
        </LinearLayout>
    
    </ScrollView>
    

    If the check boxes count are dynamic, then you might need to use a RecyclerView with 2 view types (one for a normal option, and the other for the custom options) instead.