gpt4 book ai didi

android - 在 SingleChoice 警报对话框的 OnClick() 中存储 CheckedItemPosition

转载 作者:行者123 更新时间:2023-11-29 21:42:00 25 4
gpt4 key购买 nike

我正在尝试存储和使用单选警报对话框的选定项目。

到目前为止,这是我的代码:

            final String[] deviceNames = getBTPairedDeviceNames();
int selpos;

new AlertDialog.Builder(this)
.setSingleChoiceItems(deviceNames, 0, null)
.setPositiveButton("O.K.", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
int selectedPosition = ((AlertDialog)dialog).getListView().getCheckedItemPosition();
// Do something useful with the position of the selected radio button

selpos = selectedPosition;
}
})
.show();

Toast.makeText(this, "" + selpos, Toast.LENGTH_SHORT) .show();

尝试分配给 selpos 时出现编译错误。错误如下:

“不能在不同方法中定义的内部类中引用非最终变量 selpos”

将 selpos 设置为最终错误结果:

“无法分配最终局部变量 selpos,因为它是在封闭类型中定义的”

如何从代码块中获取所选项目的位置?

谢谢

最佳答案

最简单的方法是在您的类中(而不是在您的函数中)将变量声明为一个字段。

int selpos; //declare in class scope

public void yourFunction() {

//don't declare here
//int selpos;

new AlertDialog.Builder(this)
.setSingleChoiceItems(deviceNames, 0, null)
.setPositiveButton("O.K.", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
int selectedPosition = ((AlertDialog)dialog).getListView().getCheckedItemPosition();
// Do something useful with the position of the selected radio button

selpos = selectedPosition;
}
})
.show();
}

关于android - 在 SingleChoice 警报对话框的 OnClick() 中存储 CheckedItemPosition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16818243/

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