【问题标题】:Looping through ArrayList or ArrayDapter of ListView or the ListView itself (Android)?循环遍历 ListView 的 ArrayList 或 ArrayDapter 或 ListView 本身(Android)?
【发布时间】:2020-10-07 03:05:08
【问题描述】:

我想知道在 Android Studio 中访问列表视图项目的最佳做法是哪种方式。 我是从数组列表、数组适配器还是列表视图本身访问它们?

例如

我想遍历列表视图的项目:

ListView listView = findViewById(R.id.listView);
ArrayList <String> arrayList = new ArrayList<String>();
arrayList.add("x");
arrayList.add("y");
ArrayAdapter <String> arrayAdapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(arrayAdapter);

方法一:

for(int i = 0; i < 2; i++)
{
        arrayList.get(i);
}

方法二:

for(int i = 0; i < 2; i++)
{
        arrayAdapter.getItem(i);
}

方法三:


for(int i = 0; i < 2; i++)
{
        listView.getItemAtPosition(i).toString();
}

注意:代码不是为测试而编写的。我只是问哪种方式是访问列表查看项目的最佳实践(复杂性方面),因为我相信所有 3 种方法都会产生相同的结果。

【问题讨论】:

    标签: java android android-studio


    【解决方案1】:

    最佳做法是通过listview获取item(方法3)

    在方法1和方法2中,你必须在将列表或适配器分配给ListView后持有它的引用

    在方法 3 中,ListView 在内部调用适配器,并且在返回对象之前已在方法中进行了所有必要的检查。

    ListView 源代码

     /**
     * Gets the data associated with the specified position in the list.
     *
     * @param position Which data to get
     * @return The data associated with the specified position in the list
     */
    public Object getItemAtPosition(int position) {
        T adapter = getAdapter();
        return (adapter == null || position < 0) ? null : adapter.getItem(position);
    }
    

    【讨论】:

      猜你喜欢
      • 2010-11-22
      • 1970-01-01
      • 2020-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-05
      • 1970-01-01
      • 2017-03-27
      相关资源
      最近更新 更多