You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spinner中展示列表指定索引的项

筛选指定项并排序后展示在Spinner中

首先需要明确:你提到的“索引为4、11、6”应该是指数据对象中的id字段(原响应列表的实际索引是0-3,不存在这些索引值)。以下是实现步骤:

1. 定义目标ID列表(按期望的展示顺序)

先把需要保留的ID按你想要的展示顺序列出来:

// Kotlin
val targetIds = listOf(4, 11, 6)
// Java
List<Integer> targetIds = Arrays.asList(4, 11, 6);

2. 筛选并排序数据

从接口返回的result列表中筛选出ID匹配的项,再按照目标ID列表的顺序排序:

// Kotlin
// 假设response是你的接口响应对象
val filteredSortedList = response.result
    .filter { targetIds.contains(it.id) } // 筛选出目标ID的项
    .sortedBy { targetIds.indexOf(it.id) } // 按目标列表顺序排序
// Java
// 假设response是接口响应对象,result为List<YourDataModel>
List<YourDataModel> filteredSortedList = new ArrayList<>();
// 先筛选目标项
for (YourDataModel item : response.getResult()) {
    if (targetIds.contains(item.getId())) {
        filteredSortedList.add(item);
    }
}
// 按目标ID列表的顺序排序
filteredSortedList.sort((a, b) -> {
    int indexA = targetIds.indexOf(a.getId());
    int indexB = targetIds.indexOf(b.getId());
    return Integer.compare(indexA, indexB);
});

3. 绑定到Spinner适配器

将处理后的列表设置为Spinner的数据源:

// Kotlin
val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, filteredSortedList.map { it.name })
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
yourSpinner.adapter = adapter
// Java
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item);
for (YourDataModel item : filteredSortedList) {
    adapter.add(item.getName());
}
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
yourSpinner.setAdapter(adapter);

补充说明

如果确实需要按列表索引筛选(但你的示例数据仅有4项,索引最大为3,不存在4、11、6这些索引),可以调整筛选逻辑为判断项在原列表中的索引是否在目标集合中,但这种情况在你的示例场景下不成立,因此优先按id字段处理。

内容的提问来源于stack exchange,提问作者ayaz khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 08:06:51