首页 > 解决方案 > 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 orais 14:00 - 15:00,我要获取索引,即 is 4

有没有办法帮助我做到这一点?谢谢!

标签: javaandroid

解决方案


此方法将返回整数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);


推荐阅读