我有一个MultiChoice AlertDialog,我有25个选择。
我想让用户只选择25个中的任意5个。
当她选择第6个选项时,我想解开它,并显示Toast信息,说明她只能做出5个选择。
MultiChoice AlertDialog可以吗?请帮忙!
答案 0 :(得分:11)
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);
}
}
});
答案 1 :(得分:2)
创建一个静态变量" 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();
}
}
答案 2 :(得分:1)
我使用的不是 LunaVulpo 的解决方案
if (((AlertDialog) dialog).getListView().getCheckedItemCount() > 2) {
...
}
因为当用户再次打开 Alertdialog 以编辑他的选择时,计数会重置,而选中的项目仍然保留。