Parcelable
文档说CREATOR
字段必须是静态的,但当我尝试以这种方式实现它时,我得到错误"内部类不能有静态声明"。
我试图通过将CategoryButton
放在一个单独的类中来解决此问题(不将其声明为MainActivity
中的内部类),但我无法调用getApplicationContext()
传递给super的构造函数。
public class MainActivity extends ActionBarActivity {
private class CategoryButton extends Button implements Parcelable{
private ArrayList<CategoryButton> buttons = null;
private RelativeLayout.LayoutParams params = null;
public CategoryButton(Context context){
super(context);
};
public void setButtons(ArrayList<CategoryButton> buttons){
this.buttons = buttons;
}
public void setParams(RelativeLayout.LayoutParams params){
this.params = params;
}
public ArrayList<CategoryButton> getButtons(){
return this.buttons;
}
public RelativeLayout.LayoutParams getParams(){
return this.params;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeList(buttons);
}
public static final Parcelable.Creator<CategoryButton> CREATOR // *** inner classes cannot have static declarations
= new Parcelable.Creator<CategoryButton>() {
public CategoryButton createFromParcel(Parcel in) {
return new CategoryButton(in); // *** 'package.MainActivity.this' cannot be referenced from a static context
}
public CategoryButton[] newArray(int size) {
return new CategoryButton[size];
}
};
private CategoryButton(Parcel in) {
super(getApplicationContext());
in.readList(buttons, null);
}
}
// ...other activity code
答案 0 :(得分:3)
您需要将CategoryButton
设置为内部静态,即
private static class CategoryButton extends Button implements Parcelable {
...