我有一个MultiChoice AlertDialog,在那里我有25个选择。
我想让用户只选择任何5个中的25个。
当她选择第六种选择时,我想对它进行检查,并显示一条祝酒词,上面说她只能做出5种选择。
有可能用MultiChoice AlertDialog吗?请帮帮我!
发布于 2014-04-01 10:18:29
创建一个静态变量"count“,并在选中的选项上增加它,并在复选框的onclick事件上取消其选中时递减。详情如下:
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class AlertWithCheckBoxActivity extends Activity {
/** Called when the activity is first created. */
static int count = 0;
final CharSequence[] items={".NET","J2EE","PHP"};
boolean[] itemsChecked = new boolean[items.length];
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void showDialog(View v)
{
count = 0;
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Pick a Choice");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String selectedTech="Selected Tech - ";
for (int i = 0; i < items.length; i++) {
if (itemsChecked[i]) {
selectedTech=selectedTech+items[i]+" ";
itemsChecked[i]=false;
}
}
}
});
builder.setMultiChoiceItems(items, new boolean[]{false,false,false}, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if(isChecked) {
if(count < 5) {
itemsChecked[which] = isChecked;
count++;
}else{
//Display your toast here
}
}else{
count--;
}
}
});
builder.show();
}
}发布于 2015-10-19 13:10:27
OP的确切解决方案是:
final boolean[] selected = new boolean[25];
builder.setMultiChoiceItems(R.array.values, selected, new DialogInterface.OnMultiChoiceClickListener() {
int count = 0;
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
count += isChecked ? 1 : -1;
selected[which] = isChecked;
if (count > 5) {
Toast.makeText(getActivity(), "You selected too many.", Toast.LENGTH_SHORT).show();
selected[which] = false;
count--;
((AlertDialog) dialog).getListView().setItemChecked(which, false);
}
}
});发布于 2020-12-24 21:21:04
我用的不是LunaVulpo的解决方案
if (((AlertDialog) dialog).getListView().getCheckedItemCount() > 2) {
...
}因为当用户再次打开opens对话框以编辑他的选择时,计数重置,而选中的项仍然保留。
https://stackoverflow.com/questions/22781502
复制相似问题