我有一个班级用于管理我的应用程序中的位图。 它需要传递给它的上下文才能使用getResources()
。 问题是我相信你不能在Parcelable类中使用Context。安卓系统 - 替代使用上下文的内容
任何人有一个解决方案的任何想法? 下面是我的代码:
public class ImageManager implements Parcelable {
private static final long serialVersionUID = 66;
private HashMap<Integer, Bitmap> mBitmaps;
private HashMap<Integer, Drawable> mDrawables;
//private Context mContext;
private boolean mActive = true;
public ImageManager(Context c) {
mBitmaps = new HashMap<Integer, Bitmap>();
mDrawables = new HashMap<Integer, Drawable>();
//mContext = c;
}
public ImageManager(Parcel in) {
// TODO Auto-generated constructor stub
}
public Bitmap getBitmap(int resource) {
if (mActive) {
if (!mBitmaps.containsKey(resource)) {
mBitmaps.put(resource,
BitmapFactory.decodeResource(mContext.getResources(), resource));
}
return mBitmaps.get(resource);
}
return null;
}
public Drawable getDrawable(int resource) {
if (mActive) {
if (!mDrawables.containsKey(resource)) {
mDrawables.put(resource, mContext.getResources().getDrawable(resource));
}
return mDrawables.get(resource);
}
return null;
}
public void recycleBitmaps() {
Iterator itr = mBitmaps.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry e = (Map.Entry)itr.next();
((Bitmap) e.getValue()).recycle();
}
mBitmaps.clear();
}
public ImageManager setActive(boolean b) {
mActive = b;
return this;
}
public boolean isActive() {
return mActive;
}
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeValue(mBitmaps);
dest.writeValue(mDrawables);
//dest.writeValue(mContext);
dest.writeByte((byte) (mActive ? 0x01 : 0x00));
}
public static final Parcelable.Creator<ImageManager> CREATOR = new Parcelable.Creator<ImageManager>() {
public ImageManager createFromParcel(Parcel in) {
return new ImageManager(in);
}
public ImageManager[] newArray(int size) {
return new ImageManager[size];
}
};
}
你做错了什么。一个“经理”通常不能是可Parcelable或Serializable。 –
同意。你为什么首先做这个“Parcelable”?除此之外,欢迎您添加一个'setContext()'setter,以便收件人在收到时可以附加一个'Context'。 – CommonsWare
这样我就可以将它传递给其他活动,以便他们可以访问位图。 – user1290717