แสดงไดอะล็อกด้วย AlertDialog.setMultiChoiceItems

ไฟล์ที่เกี่ยวข้อง
- activity_main.xml
- MainActivity.java
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Multiple choice dialog"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.phaisarn.myapplication;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<Integer> arrayList = new ArrayList<>();
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String[] items = {"2559", "2560", "2561", "2562"};
boolean[] isSelected = new boolean[4];
for (int i : arrayList) {
isSelected[i] = true;
}
new AlertDialog.Builder(MainActivity.this)
.setTitle("Multiple choice dialog")
.setMultiChoiceItems(items, isSelected, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
arrayList.add(which);
} else if (arrayList.contains(which)) {
arrayList.remove(Integer.valueOf(which));
}
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String str = "";
for (int i : arrayList) {
str += " " + items[i] + "\n";
}
str = str.substring(0, str.length() - 1);
if (str.length() > 0) {
Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
}
}
})
.show();
}
});
}
}
บรรทัดที่ 21: สร้างตัวแปร arrayList ไว้จดจำตัวเลือกที่ถูกเลือก
บรรทัดที่ 27: กำหนดให้มีตัวเลือก 4 ตัว เก็บไว้ใน items
บรรทัดที่ 28: สร้างตัวแปร isSelected ไว้รับค่าตัวเลือกที่ถูกเลือกจาก arrayList เพื่อนำไปกำหนดให้ MultiChoice
บรรทัดที่ 34: นำตัวเลือก items และค่าตัวเลือกที่ถูกเลือกจาก isSelected ไปใช้ด้วยเมธอด setMultiChoiceItems()
บรรทัดที่ 44: กำหนดปุ่ม PositiveButton
บรรทัดที่ 49: นำค่าของตัวเลือกที่ถูกเลือกมาเก็บไว้ในตัวแปร str
บรรทัดที่ 51: ลบเครื่องหมาย \n ตัวสุดท้ายออก