以编程方式设置微调器的选定项

本文讨论了在Android项目中,如何以编程方式设置Spinner(微调器)的选定项。提供了多种方法,包括直接设置索引、通过值查找位置再设置,以及在UI线程中设置选中项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文翻译自:Set selected item of spinner programmatically

I am working on an android project and I am using a spinner which uses an array adapter which is populated from the database. 我正在研究一个android项目,我正在使用一个使用数组适配器的微调器,该数组适配器是从数据库中填充的。

I can't find out how I can set the selected item programmatically from the list. 我无法找到如何从列表中以编程方式设置所选项目。 For example if, in the spinner I have the following items: 例如,如果在微调器中我有以下项目:

  • Category 1 第1类
  • Category 2 第2类
  • Category 3 第3类

How would I programmatically make Category 2 the selected item when the screen is created. 创建屏幕时,如何以编程方式将类别2设为选定项目。 I was thinking it might be similar to c# IE Spinner.SelectedText = "Category 2" but there doesn't seem to be any method similar to this for Android. 我认为它可能类似于c#IE Spinner.SelectedText =“Category 2”但似乎没有任何类似于Android的方法。


#1楼

参考:https://stackoom.com/question/kSTw/以编程方式设置微调器的选定项


#2楼

使用以下命令: spinnerObject.setSelection(INDEX_OF_CATEGORY2)


#3楼

public static void selectSpinnerItemByValue(Spinner spnr, long value) {
    SimpleCursorAdapter adapter = (SimpleCursorAdapter) spnr.getAdapter();
    for (int position = 0; position < adapter.getCount(); position++) {
        if(adapter.getItemId(position) == value) {
            spnr.setSelection(position);
            return;
        }
    }
}

You can use the above like: 您可以使用以上内容:

selectSpinnerItemByValue(spinnerObject, desiredValue);

& of course you can also select by index directly like 当然你也可以直接选择索引

spinnerObject.setSelection(index);

#4楼

I have a SimpleCursorAdapter so I have to duplicate the data for use the respose in this post. 我有一个SimpleCursorAdapter所以我必须复制数据以便在这篇文章中使用respose。 So, I recommend you try this way: 所以,我建议你尝试这种方式:

for (int i = 0; i < spinnerRegion.getAdapter().getCount(); i++) {
    if (spinnerRegion.getItemIdAtPosition(i) == Integer
        .valueOf(signal.getInt(signal
            .getColumnIndexOrThrow("id_region")))) {
        spinnerRegion.setSelection(i);
        break;
    }
}

I think that is a real way 我认为这是一个真实的方式


#5楼

No one of these answers gave me the solution, only worked with this: 这些答案中没有一个给我解决方案,只有这个:

mySpinner.post(new Runnable() {
    @Override
    public void run() {
        mySpinner.setSelection(position);
    }
});

#6楼

如果你有一个联系人列表,你可以这样做:

((Spinner) view.findViewById(R.id.mobile)).setSelection(spinnerContactPersonDesignationAdapter.getPosition(schoolContact.get(i).getCONT_DESIGNATION()));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值