gpt4 book ai didi

android - 在 alertDialog 中禁用复选框项目

转载 作者:行者123 更新时间:2023-12-04 14:36:12 25 4
gpt4 key购买 nike

我通过警报对话框提供数组以选择多个选项如果数组已满,我想禁用选择

我已经能够在达到限制后停止向数组添加项目,但无法禁用复选框

 AlertDialog.Builder builder=new AlertDialog.Builder(this);
View view=inflater.inflate(R.layout.dialog_genre,null,false);
builder.setView(view).setTitle("Select Genres");

builder.setMultiChoiceItems(array, checkedGenres, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if(isChecked) {
if (!selectedgenre.contains(String.valueOf(which)))
if(selectedgenre.size()<5)
{
selectedgenre.add(String.valueOf(which));
checkedGenres[which]=true;
}
else{
Toast.makeText(getApplicationContext(),"you can't add more genres",Toast.LENGTH_LONG).show();
}
}
else if (selectedgenre.contains(String.valueOf(which)))
{
selectedgenre.remove(String.valueOf(which));
checkedGenres[which]=false;
}
}
}

enter image description here

最佳答案

ListView 中的 View 是可重用的,所以 items aren't really linked to a view .但是,您可以在将 View 添加到 AlertDialog 的 ListView 内的 ListView 时启用或禁用 View 。 ViewGroup.setOnHierarchyChangeListener让你这样做。

    final CharSequence[] items = new CharSequence[]
{"9×19mm Sidearm", ".40 Dual Elites", "228 Compact", "Night Hawk .50C"};
boolean[] checkedItems = new boolean[]{false, false, true, true};
final boolean[] disabledItems = new boolean[]{false, true, false, true};

Context context = this;
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
dialogBuilder.setTitle("Select your pistol");

dialogBuilder.setMultiChoiceItems(items, checkedItems,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i, boolean checked) {

}
});

AlertDialog alertDialog = dialogBuilder.create();
alertDialog.getListView().setOnHierarchyChangeListener(
new ViewGroup.OnHierarchyChangeListener() {
@Override
public void onChildViewAdded(View parent, View child) {
CharSequence text = ((AppCompatCheckedTextView)child).getText();
int itemIndex = Arrays.asList(items).indexOf(text);
child.setEnabled(disabledItems[itemIndex]);
}

@Override
public void onChildViewRemoved(View view, View view1) {
}
});

alertDialog.show();

Outcome of code sample (Android 9, API 28)

请注意 setEnable不会避免 clickListeners 触发。如果您不想点击复选框,请添加 child.setOnClickListener(null) .

关于android - 在 alertDialog 中禁用复选框项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39053333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com