首页 > 解决方案 > 如何使用 Parcelable 从 arraylist 索引传递元素?

问题描述

在比赛中,我需要将数组索引的所有元素传递给另一个活动。这就是我所拥有的...

    Intent LocationReview = new Intent(v.getContext(), ReviewActivity.class);
     // iterate through array 
    for (int i = 0; i < locationReview.size(); i++) {

int locationID = locationReview.get(i).id;
int currentID = Integer.parseInt(tvId.getText().toString());

          // compare id no. at index i of array
          if ((locationReview.get(i).id == Integer.parseInt(tvId.getText().toString()))) {

          // if match set putExtra array to locationReview.get(i)
              **LocationReview.putParcelableArrayListExtra("locationReview", locationReview.get(i));**
              itemView.getContext().startActivity(LocationReview);
              } else {
                Log.e("VerticalAdapter", "no matcon on locationReview");
               }
           }

if 语句比较idlocationReview 数组中的元素。如果元素与文本视图中的字符串匹配,我需要数组索引i及其所有元素,将其添加为可使用的数组并作为 Extra 添加到我的意图中。

标签: javaandroidarraysparcelable

解决方案


我会将解决方案分为几个步骤:

步骤 1.确保您的 ArrayList 模型类实现Parcelable接口。

步骤 2.遍历locationReview数组的所有元素,以确定它的哪些索引符合您的要求。您可以在类中定义另一个“过滤”的 ArrayList 对象,并使用由您的(locationReview.get(i).id == Integer.parseInt(tvId.getText().toString()))条件过滤的项目填充它。

ArrayList<Object> filteredlocationReview = new ArrayList<>();
    for (int i = 0; i < locationReview.size(); i++) {

        int locationID = locationReview.get(i).id;
        int currentID = Integer.parseInt(tvId.getText().toString());

        // compare id no. at index i of array
        if ((locationReview.get(i).id == Integer.parseInt(tvId.getText().toString()))) {
            filteredlocationReview.add(locationReview.get(i))
        }
    }

步骤 3.超出循环范围,将过滤后的 Parcelable 数组通过

LocationReview.putParcelableArrayListExtra("locationReview", filteredlocationReview);

第 4 步。开始新的活动,您需要使用getParcelableArrayListExtra方法来获取您的数组。


推荐阅读