📜  如何在 Android 中实现 MultiSelect DropDown?

📅  最后修改于: 2022-05-13 01:55:37.727000             🧑  作者: Mango

如何在 Android 中实现 MultiSelect DropDown?

在本文中,我们将看到如何在 android studio 中创建 MultiSelect DropDown 并从下拉列表中选择多个项目。 MultiSelect DropDown 的优点。

  • 它是列表框的一个很好的替代品,因为它占用的空间更少,并且与列表框的工作相同,并且为 UI 提供了良好的外观。
  • 下拉列表是大多数用户熟悉的选择机制,因为它们在 web 和 android 应用程序中都被广泛使用。
  • 用户可以选择多个他/她喜欢的项目。

我们将在本文中构建什么?

在本文中,我们将使用一个 TextView,我们将在该 TextView 上设置一个 onClickListener,这样每当用户点击它时就会出现下拉列表。在下拉列表中,我们将提供一个功能来选择和多个项目,清除所选项目,以及一个取消选择过程的按钮。请注意,我们将使用Java语言实现此应用程序。下面给出了一个示例视频,以了解我们将在本文中做什么。

分步实施

第 1 步:创建一个新项目

  • 打开一个新项目。
  • 我们将使用Java语言处理 Empty Activity。保持所有其他选项不变。
  • 您可以在方便时更改项目的名称。
  • 将有两个名为activity_main.xml 和 MainActivity 的默认文件。Java

如果您不知道如何在 Android Studio 中创建新项目,那么您可以参考如何在 Android Studio 中创建/启动新项目?

第 2 步:处理 activity_main.xml 文件



在这里,我们将设计应用程序的用户界面。我们将在各自的作品中使用以下组件:

  • TextView:允许用户点击它,以便出现一个下拉列表并显示其中的所选项目。
  • 下拉箭头:向用户表明点击后将完成某项操作。

activity_main.xml文件中使用以下代码。

XML



  
    
    
      


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 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(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();
            }
        });
    }
}


执行完上面的代码设计的activity_main.xml文件是这样的。

第 3 步:使用 MainActivity。 Java文件

转到主活动。 Java文件,参考如下代码。下面是MainActivity的代码。 Java文件。代码中添加了注释以更详细地理解代码。

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 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(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();
            }
        });
    }
}

恭喜!我们已经在 android studio 中成功实现了 MultiSelect 下拉菜单。这是我们应用程序的最终输出。

输出: