设置LayoutParams时出现NullPointerException [英] NullPointerException while setting LayoutParams
问题描述
我想以编程方式添加一个按钮,也应该设置LayoutParams。
不幸的是,该应用程序给出了一个例外:
I want to add a button programmatically, which LayoutParams should be set too. Unfortunaly the app gives an exception:
java.lang.NullPointerException:尝试写入字段'int
在null对象引用上的android.view.ViewGroup $ LayoutParams.height'
java.lang.NullPointerException: Attempt to write to field 'int android.view.ViewGroup$LayoutParams.height' on a null object reference
我不知道,为什么。你可以帮帮我吗?
这是我的代码。
I have no idea, why. Could you help me? Here is my code.
Button b = new Button(getApplicationContext());
b.setText(R.string.klick);
ViewGroup.LayoutParams params = b.getLayoutParams();
params.height = ViewGroup.LayoutParams.MATCH_PARENT;
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
推荐答案
由于您是以编程方式创建Button b
将不会设置任何布局参数。所以你需要像这样手动设置它们:
Since you are creating a Button programmatically b
will not have any layout params set. So you'll need to set them manually like this:
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
b.setLayoutParams(params);
或至少在更改之前检查params是否为空
Or at least check if params are not null before changing them
ViewGroup.LayoutParams params = b.getLayoutParams();
if (params != null) {
params.width= ViewGroup.LayoutParams.MATCH_PARENT;
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
} else
params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
这篇关于设置LayoutParams时出现NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!