java - 为什么我的 linearLayout 的行为就像它是空的
问题描述
当我尝试将在对象中创建的按钮添加到 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)
解决方案
尝试用关键字替换 Button 声明中的上下文,this
如下所示:
button = new Button(this);
代替:
button = new Button(context);
如果上述解决方案不起作用,还可以尝试将 Button 设为全局。
推荐阅读
- amazon-web-services - 无法通过 yum 为 AWS jupyter 终端安装 boost-1.70.0
- python - 转换为列出每个值都是python中的字典
- app-store - 如何获取 AppStore 应用图片的链接?
- ruby-on-rails-5 - 为什么 Payments.valid.first.source 为 Spree::Order 返回 nil 的某些原因?
- c# - Entity Framework Core - 线程安全和锁上下文锁定{}。我的选择合适吗?
- hadoop - TEZ 参数等效于“mapreduce.map.failures.maxpercent”
- java - Android - 自定义 Toast 类中的程序 ImageView 约束
- python-3.x - 如何从具有相同类属性的表中抓取文本?
- javascript - 如何从特定频道获取附件 url?
- c - 具有 o(1) 的数组