【问题标题】:Android - Parcelable | putParcelableArrayListExtra("ListItems", listItems);Android - 可打包 | putParcelableArrayListExtra("ListItems", listItems);
【发布时间】:2016-03-21 03:33:04
【问题描述】:

我正在尝试将 MyItem 对象的 ArrayList 从一个活动传递到另一个活动。据我了解,我需要在 MyItem 类中实现 Parcable。所以这就是我到目前为止所做的:

public class MyItem implements ClusterItem, Parcelable {
    private LatLng mPosition=null;
    private String aString;

    public MyItem(double lat, double lng, String aString) {
        mPosition = new LatLng(lat, lng);
        this.aString= aString;
    }

    @Override
    public LatLng getPosition() {
        return mPosition;
    }

    public String getString(){
        return aString;
    }


    public int describeContents() {
        return 0;
    }


    public void writeToParcel(Parcel dest, int flags) {
        //dest.writeLngLat ?
        dest.writeString(postID);
    }

    public static final Parcelable.Creator<MyItem> CREATOR
            = new Parcelable.Creator<MyItem>() {
        public MyItem createFromParcel(Parcel in) {
            return new MyItem(in);
        }

        public MyItem[] newArray(int size) {
            return new MyItem[size];
        }
    };

    private MyItem(Parcel in) {
        //mPosition = in.readLngLat ?
        aString = in.readString();
    }
}

第一个问题:如何在 writeToParcel 中写入 LngLat 字段,如何在 MyItem(Parcel in) 构造函数中清除它?

第二个问题:这是否足以让这段代码工作?

                    ArrayList<MyItem> listItems = new ArrayList<>();
                    Iterator<MyItem> items = cluster.getItems().iterator();
                    while (items.hasNext()) {
                        listItems.add(items.next());
                    }
                    Intent intent = new Intent(MapsActivity.this, ClusterPosts.class);
                    intent.putParcelableArrayListExtra("oO", listItems);
                    startActivity(intent);

然后在 CluserPosts 中:

    Intent intent = getIntent();
    ArrayList<MyItem> post = intent.getParcelableArrayListExtra("oO");
    for(MyItem item : post){
        Log.d("elaela", item.getString());
    }

【问题讨论】:

  • LatLngParcelable,对吧?
  • LatLng 是来自谷歌地图 api 的“默认”对象,不是由我实现的。但我认为它实际上是可包裹的
  • 所以它是Parcelable,然后直接从Parcel读/写它

标签: java android android-intent parcelable


【解决方案1】:

包裹写成-

dest.writeDouble(mPosition.latitude);
dest.writeDouble(mPosition.longitude);

【讨论】:

    【解决方案2】:

    您可以将纬度和经度作为双精度写到目的地,然后形成一个位置。

    dest.writeDouble(lat);
    dest.writeDouble(long);
    

    【讨论】:

      猜你喜欢
      • 2015-10-04
      • 1970-01-01
      • 2020-11-28
      • 2020-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-13
      • 2012-09-15
      相关资源
      最近更新 更多