[关闭]
@natsumi 2016-07-06T09:47:33.000000Z 字数 2112 阅读 1343

用intent传递ArrayList<自定义类型>

Android


首先自定义类型需要实现Parcelable接口

  1. package bupt.tiantian.weibo.helper;
  2. import android.os.Parcel;
  3. import android.os.Parcelable;
  4. import android.text.TextUtils;
  5. import java.util.regex.Matcher;
  6. /**
  7. * Created by tiantian on 16-7-6.
  8. */
  9. public class PicUrl implements Parcelable {
  10. private String mThumbnailUrl = null;
  11. private String mMiddleUrl = null;
  12. private String mLargeUrl = null;
  13. public PicUrl(String thumbnailUrl) {
  14. if (!TextUtils.isEmpty(thumbnailUrl)) {
  15. this.mThumbnailUrl = thumbnailUrl;
  16. Matcher matcher = PicUrlHolder.THUMB_PATTERN.matcher(thumbnailUrl);
  17. this.mMiddleUrl = matcher.replaceFirst(PicUrlHolder.MIDDLE_PIC_STRING);
  18. }
  19. }
  20. public String getThumbnailUrl() {
  21. return mThumbnailUrl;
  22. }
  23. public String getMiddleUrl() {
  24. if (mMiddleUrl != null) {
  25. return mMiddleUrl;
  26. } else if (mThumbnailUrl != null) {
  27. Matcher matcher = PicUrlHolder.THUMB_PATTERN.matcher(mThumbnailUrl);
  28. mMiddleUrl = matcher.replaceFirst(PicUrlHolder.MIDDLE_PIC_STRING);
  29. return mMiddleUrl;
  30. } else {
  31. return null;
  32. }
  33. }
  34. public String getLargeUrl() {
  35. if (mLargeUrl != null) {
  36. return mLargeUrl;
  37. } else if (mThumbnailUrl != null) {
  38. Matcher matcher = PicUrlHolder.THUMB_PATTERN.matcher(mThumbnailUrl);
  39. mLargeUrl = matcher.replaceFirst(PicUrlHolder.LARGE_PIC_STRING);
  40. return mLargeUrl;
  41. } else {
  42. return null;
  43. }
  44. }
  45. /*以下代码为实现parcelable添加*/
  46. protected PicUrl(Parcel in) {
  47. mThumbnailUrl = in.readString();
  48. mMiddleUrl = in.readString();
  49. mLargeUrl = in.readString();
  50. }
  51. public static final Creator<PicUrl> CREATOR = new Creator<PicUrl>() {
  52. @Override
  53. public PicUrl createFromParcel(Parcel in) {
  54. return new PicUrl(in);
  55. }
  56. @Override
  57. public PicUrl[] newArray(int size) {
  58. return new PicUrl[size];
  59. }
  60. };
  61. @Override
  62. public int describeContents() {
  63. return 0;
  64. }
  65. @Override
  66. public void writeToParcel(Parcel dest, int flags) {
  67. dest.writeString(mThumbnailUrl);
  68. dest.writeString(mMiddleUrl);
  69. dest.writeString(mLargeUrl);
  70. }
  71. }

将ArrayList传入intent
也可以不用bundle直接i.putExtra(...)

  1. Intent i = new Intent(mContext, OriginPictureActivity.class);
  2. Bundle bundle = new Bundle();
  3. bundle.putInt("position", position);
  4. bundle.putParcelableArrayList("url", mPicUrlHolder.getPicUrlList());
  5. i.putExtras(bundle);
  6. mContext.startActivity(i);

从intent读取数据

  1. Intent i = getIntent();
  2. Bundle bundle = i.getExtras();
  3. ArrayList<PicUrl> picUrls = bundle.getParcelableArrayList("url");
  4. int position = bundle.getInt("position");
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注