gpt4 book ai didi

java - 无法实现 Parcelable,因为我无法将 CREATOR 字段设为静态

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:09:48 25 4
gpt4 key购买 nike

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

最佳答案

您需要将您的CategoryButton 设置为内部静态,即

private static class CategoryButton extends Button implements Parcelable {
...

关于java - 无法实现 Parcelable,因为我无法将 CREATOR 字段设为静态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31363496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com