java - Android - 通过文本查找 ListView 项的索引
问题描述
我有两个字符串列表。一个包含 ListView 的项目,另一个包含第一个列表中的一些项目。
让我告诉你:这基本上是我的 ListView,我们称之为Ore
:
<string-array name="ore">
<item>10:00 - 11:00</item>
<item>11:00 - 12:00</item>
<item>12:00 - 13:00</item>
<item>13:00 - 14:00</item>
<item>14:00 - 15:00</item>
<item>15:00 - 16:00</item>
<item>16:00 - 17:00</item>
<item>17:00 - 18:00</item>
<item>18:00 - 19:00</item>
<item>19:00 - 20:00</item>
<item>20:00 - 21:00</item>
<item>21:00 - 22:00</item>
</string-array>
这是我的第一个列表(它来自我的,strings.xml
但我已经设法将其转换为字符串列表)。
第二个列表,我们称之为CheckOre
:
12:00 - 13:00, 19:00 - 20:00, 15:00 - 16:00
for(String ora : CheckOre){
for(String stringOra: Ore){
if(ora.equals(stringOra)){
// i want to get the index of ListView item by the text from Ore
}
}
}
正如它在if
条件中所说,我想通过文本获取 ListView 项的索引。比如 if ora
is 14:00 - 15:00
,我要获取索引,即 is 4
。
有没有办法帮助我做到这一点?谢谢!
解决方案
此方法将返回整数ArrayList中所有相同的索引:
public ArrayList<Integer> getSameIndexes(ArrayList<String> arr1, ArrayList<String> arr2) {
ArrayList<Integer> indexes = new ArrayList<Integer>();
for(int x = 0; x < arr1.size(); x++) {
for(int y = 0; y < arr2.size(); y++) {
if(arr1.get(x).equals(arr2.get(y)))
indexes.add(y);
}
}
return indexes;
}
只需调用它getSameIndexes(CheckOre, Ore);
或者,您可以使用:
public int getIndex(ArrayList<String> arr1, ArrayList<String> arr2) {
for(int x = 0; x < arr1.size(); x++) {
for (int y = 0; y < arr2.size(); y++) {
if (arr1.get(x).equals(arr2.get(y)))
return y;
}
}
return -1;
}
这将返回调用时项目匹配的第一个元素getIndex(CheckOre, Ore);
推荐阅读
- android - 如何获取调用 Android DialogFragment onDismiss() 的原因?
- android - OpenGL Android,我有一个 3D 旋转立方体,它已经消失了
- reactjs - 以编程方式 React Native 调用 Touchable
- c# - 确保使用 nuget 包的应用程序的 bin 文件夹中的文本文件
- python - IndexError:列出超出范围的索引空间入侵者
- multithreading - 使用多线程和异步方法解析数据表
- powershell - 无法在PowerShell中移动或删除文件
- amazon-web-services - 使用 MFA 登录 Azure CLI
- javascript - 收到错误“TypeError:Page 不是构造函数”。
- google-chrome - 为什么 Chrome 不使用 Xpath 突出显示 Elements 中的元素