簡體   English   中英

為什么我的linearLayout表現為null

[英]Why does my linearLayout behave like it is null

當我嘗試將在對象中創建的按鈕添加到linearLayout時,即使按鈕已初始化,它的行為也好像按鈕為null。

我已經測試了按鈕實際上並不為null,並且線性布局已正確聲明,它是正確的。

linearLayout從onCreate()中的不為null到getLinearLayout()中的為null;

   public Province(Context context, int id, int x, int y){
        this.id = id;
        this.x = x;
        this.y = y;
        button = new Button(context); //creates button, context is passed in through the MainActivity
        selected = false;
        selection(); //selection call
    }
//selection method
    public Button selection(){
        linearLayout = getLinearLayout();  //layout from MainActivity
        button.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        linearLayout.addView(button);  //adds button to current view, button is not null despite error
        button.setId(id);
        button.setX(x);
        button.setY(y);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(getCurrentPlayer().getStage() == 0) {
                    troops++;
                    getCurrentPlayer().modTroops(-1);
                }
                else {
                    if (selected)
                        selected = false;
                    else if (!selected && getCurrentPlayer().select(0) > 0)
                        selected = true;
                }
            }
        });
        return button;
    }

這是定義linearLayout的代碼;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        linearLayout = findViewById(R.id.linear);  //refrences MainActivity xml with id linear
        //linearLayout is not null here;
        lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        map = new Map(this, 0);
    }

這是get方法:

public LinearLayout getLinearLayout(){
        if(linearLayout == null)
            throw new IllegalArgumentException("Linear Layout is null");
        //the exeption is thrown here so linearLayout is now null;
        return linearLayout;
    }

這是出現的錯誤:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.addView(android.view.View)' on a null object reference
        at com.example.hedgemonics.Province.selection(Province.java:56)
        at com.example.hedgemonics.Province.<init>(Province.java:28)
        at com.example.hedgemonics.Map.<init>(Map.java:10)
        at com.example.hedgemonics.MainActivity.onCreate(MainActivity.java:28)

嘗試使用this關鍵字替換Button聲明中的上下文,如下所示:

button = new Button(this); 

代替:

button = new Button(context);

如果上述解決方案無效,請嘗試將Button設置為全局。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM