Android MultipleSelect checkbox on Dialog box Tutorial

Objective

In this tutorial, I am going to explain process of opening a dialog box with various selectable options, select more than one option as response and use that response.

Multiple selection is a boolean attribute which specifies that multiple options can be selected at once. Checkboxes are more user-friendly and by using the them, we inform the user that multiple selection is available. The Alert Dialog box is basically a prompt window which developers use to get response from user in case of an action, by being in scope of the same activity.

 

Step 2

Creating a new project:

Create a new Project in android Studio goto File ⇒ New ⇒ New Projects.

Step 3

Making Layout

To start with, we need a button. Click on the button will open the alertdaialog box. So we will create a text view which will act as a button. Use the following code to create a text view.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<br />
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br />
&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br />
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br />
    android:layout_width=&quot;match_parent&quot;<br />
    android:layout_height=&quot;match_parent&quot;<br />
    android:paddingBottom=&quot;@dimen/activity_vertical_margin&quot;<br />
    android:paddingLeft=&quot;@dimen/activity_horizontal_margin&quot;<br />
    android:paddingRight=&quot;@dimen/activity_horizontal_margin&quot;<br />
    android:paddingTop=&quot;@dimen/activity_vertical_margin&quot;<br />
    tools:context=&quot;com.numetriclabz.multipleselectcheckbox.MainActivity&quot;&gt;</p>
<p>        &lt;RelativeLayout<br />
            android:id=&quot;@+id/openDialog&quot;<br />
            android:layout_width=&quot;match_parent&quot;<br />
            android:layout_height=&quot;40dp&quot;<br />
            android:orientation=&quot;horizontal&quot;<br />
            android:background=&quot;@android:color/holo_orange_light&quot;&gt;</p>
<p>                &lt;TextView<br />
                    android:id=&quot;@+id/text&quot;<br />
                    android:layout_width=&quot;wrap_content&quot;<br />
                    android:layout_height=&quot;wrap_content&quot;<br />
                    android:textColor=&quot;#555555&quot;<br />
                    android:singleLine=&quot;true&quot;<br />
                    android:textSize=&quot;18dp&quot;<br />
                    android:layout_centerVertical=&quot;true&quot;<br />
                    android:layout_centerHorizontal=&quot;true&quot;<br />
                    android:text=&quot;Click here to open Dialog&quot; /&gt;</p>
<p>        &lt;/RelativeLayout&gt;</p>
<p>    &lt;/RelativeLayout&gt;</p>
<p>

 

screen_1

Step 4

Creating an Array list

Now, we need a list of values that will be provided as data source to the listview of the alertdialog box. We will use an ArrayList to provide the data to list. Following is the sample of data we are going to use in this article.

1
2
3
4
5
6
<br />
 List&lt;CharSequence&gt; list = new ArrayList&lt;CharSequence&gt;();</p>
<p> for (int i=0;i&lt;20;i++){</p>
<p>         list.add(&quot;test &quot; + i);  // Add the item in the list<br />
 }</p>
<p>

 

Step 5

Creating an AlertDialog box

Next, we need to add a click listener to the layout of textview that we are using as button to open the dialog. When this layout view is clicked, the AlertDialog.builder method will set up our dialog window and populate it provided data.

Now, we need to enable the multiple selection in the dialog and here comes AlertDialog.builder’s setMultipleChoiceItem() method. This method will attach a multiple select listener with dialog interface. The list will have a check mark displayed to the right of the text for each checked item.

Clicking on an item in the list will not dismiss the dialog. After the selection, we can use the OK button to lock the choices and send response to the main activity.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
</p>
<p>import android.app.AlertDialog;<br />
import android.content.DialogInterface;<br />
import android.support.v7.app.AppCompatActivity;<br />
import android.os.Bundle;<br />
import android.util.Log;<br />
import android.view.View;<br />
import android.widget.ListView;<br />
import android.widget.TextView;</p>
<p>import java.util.ArrayList;<br />
import java.util.List;</p>
<p>public class MainActivity extends AppCompatActivity {<br />
    List&lt;CharSequence&gt; list = new ArrayList&lt;CharSequence&gt;();</p>
<p>    @Override<br />
    protected void onCreate(Bundle savedInstanceState) {<br />
        super.onCreate(savedInstanceState);<br />
        setContentView(R.layout.activity_main);</p>
<p>        for (int i=0;i&lt;20;i++){</p>
<p>            list.add(&quot;test &quot; + i);  // Add the item in the list<br />
        }</p>
<p>        View openDialog = (View) findViewById(R.id.openDialog);<br />
        openDialog.setOnClickListener(new View.OnClickListener() {</p>
<p>            @Override<br />
            public void onClick(View v) {</p>
<p>                // Intialize  readable sequence of char values<br />
                final CharSequence[] dialogList=  list.toArray(new CharSequence[list.size()]);<br />
                final AlertDialog.Builder builderDialog = new AlertDialog.Builder(MainActivity.this);<br />
                builderDialog.setTitle(&quot;Select Item&quot;);<br />
                int count = dialogList.length;<br />
                boolean[] is_checked = new boolean[count]; // set is_checked boolean false;</p>
<p>                // Creating multiple selection by using setMutliChoiceItem method<br />
                builderDialog.setMultiChoiceItems(dialogList, is_checked,<br />
                        new DialogInterface.OnMultiChoiceClickListener() {<br />
                            public void onClick(DialogInterface dialog,<br />
                                                int whichButton, boolean isChecked) {<br />
                            }<br />
                        });</p>
<p>                builderDialog.setPositiveButton(&quot;OK&quot;,<br />
                        new DialogInterface.OnClickListener() {<br />
                    @Override<br />
                    public void onClick(DialogInterface dialog, int which) {</p>
<p>                        ListView list = ((AlertDialog) dialog).getListView();<br />
                        // make selected item in the comma seprated string<br />
                        StringBuilder stringBuilder = new StringBuilder();<br />
                        for (int i = 0; i &lt; list.getCount(); i++) {<br />
                            boolean checked = list.isItemChecked(i);</p>
<p>                            if (checked) {<br />
                                if (stringBuilder.length() &gt; 0) stringBuilder.append(&quot;,&quot;);<br />
                                stringBuilder.append(list.getItemAtPosition(i));</p>
<p>                            }<br />
                        }</p>
<p>                        /*Check string builder is empty or not. If string builder is not empty.<br />
                          It will display on the screen.<br />
                         */<br />
                        if (stringBuilder.toString().trim().equals(&quot;&quot;)) {</p>
<p>                            ((TextView) findViewById(R.id.text)).setText(&quot;Click here to open Dialog&quot;);<br />
                            stringBuilder.setLength(0);</p>
<p>                        } else {</p>
<p>                            ((TextView) findViewById(R.id.text)).setText(stringBuilder);<br />
                        }<br />
                    }<br />
                });</p>
<p>                builderDialog.setNegativeButton(&quot;Cancel&quot;,<br />
                        new DialogInterface.OnClickListener() {<br />
                            @Override<br />
                            public void onClick(DialogInterface dialog, int which) {<br />
                                ((TextView) findViewById(R.id.text)).setText(&quot;Click here to open Dialog&quot;);<br />
                            }<br />
                        });<br />
                AlertDialog alert = builderDialog.create();<br />
                alert.show();<br />
            }<br />
        });<br />
    }<br />
}</p>
<p>

 

screen_2screen_3

screen_4

 

 

Advertisements
This entry was posted in Android Development. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s