Saturday, December 28, 2024
Google search engine
HomeLanguagesJavaHow to Implement MultiSelect DropDown in Android?

How to Implement MultiSelect DropDown in Android?

In this article, we are going to see how we can make a MultiSelect DropDown in android studio and will select multiple items from a dropdown list. Advantages of MultiSelect DropDown.

  • It is a good replacement for list boxes as it uses less space does the same work as a list box and gives a good look to UI.
  • Dropdown lists are familiar selection mechanisms for most users since they are widely used both on the web and in android apps.
  • User can select more than one item which he/she likes.

What we are going to build in this article?

In this article, we will be using a TextView, and we will set an onClickListener on that TextView so that whenever the user clicks on it dropdown list occurs. In the dropdown list, we will provide a feature to select multiple items, clear selected items, and a Button for canceling the selection process. Note that we are going to implement this application using Java language. A sample video is given below to get an idea about what we are going to do in this article.

Step by Step Implementation

Step 1: Creating a new project

  • Open a new project.
  • We will be working on Empty Activity with language as Java. Leave all other options unchanged.
  • You can change the name of the project at your convenience.
  • There will be two default files named activity_main.xml and MainActivity.java.

If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio? 

Step 2: Working on activity_main.xml file

Here we will design the user interface of our application. We will be using the following components for their respective works:

  • TextView: To allow users to click on it so that a dropdown list can appear and display the selected items in it.
  • Drop-down arrow: to indicate to the user that some action will be completed after clicking it.

Use the following code in the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<!-- Relative layout as parent layout-->
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity">
 
    <!-- text view to display selected items-->
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@android:drawable/editbox_background"
        android:drawableRight="@android:drawable/arrow_down_float"
        android:drawablePadding="16dp"
        android:hint="Select Language"
        android:padding="12dp" />
     
</RelativeLayout>


After executing the above code design of the activity_main.xml file looks like this.

Step 3: Working with MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
 
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
 
import java.util.ArrayList;
import java.util.Collections;
 
public class MainActivity extends AppCompatActivity {
     
    // initialize variables
    TextView textView;
    boolean[] selectedLanguage;
    ArrayList<Integer> langList = new ArrayList<>();
    String[] langArray = {"Java", "C++", "Kotlin", "C", "Python", "Javascript"};
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // assign variable
        textView = findViewById(R.id.textView);
 
        // initialize selected language array
        selectedLanguage = new boolean[langArray.length];
 
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                 
                // Initialize alert dialog
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
 
                // set title
                builder.setTitle("Select Language");
                 
                // set dialog non cancelable
                builder.setCancelable(false);
 
                builder.setMultiChoiceItems(langArray, selectedLanguage, new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i, boolean b) {
                        // check condition
                        if (b) {
                            // when checkbox selected
                            // Add position  in lang list
                            langList.add(i);
                            // Sort array list
                            Collections.sort(langList);
                        } else {
                            // when checkbox unselected
                            // Remove position from langList
                            langList.remove(Integer.valueOf(i));
                        }
                    }
                });
 
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // Initialize string builder
                        StringBuilder stringBuilder = new StringBuilder();
                        // use for loop
                        for (int j = 0; j < langList.size(); j++) {
                            // concat array value
                            stringBuilder.append(langArray[langList.get(j)]);
                            // check condition
                            if (j != langList.size() - 1) {
                                // When j value  not equal
                                // to lang list size - 1
                                // add comma
                                stringBuilder.append(", ");
                            }
                        }
                        // set text on textView
                        textView.setText(stringBuilder.toString());
                    }
                });
 
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // dismiss dialog
                        dialogInterface.dismiss();
                    }
                });
                builder.setNeutralButton("Clear All", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // use for loop
                        for (int j = 0; j < selectedLanguage.length; j++) {
                            // remove all selection
                            selectedLanguage[j] = false;
                            // clear language list
                            langList.clear();
                            // clear text view value
                            textView.setText("");
                        }
                    }
                });
                // show dialog
                builder.show();
            }
        });
    }
}


Output:

RELATED ARTICLES

Most Popular

Recent Comments