繁体   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