java 设置 LayoutParams 时出现 NullPointerException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36340268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NullPointerException while setting LayoutParams
提问by snowparrot
I want to add a button programmatically, which LayoutParams should be set too. Unfortunaly the app gives an exception:
我想以编程方式添加一个按钮,也应该设置 LayoutParams。不幸的是,该应用程序给出了一个例外:
java.lang.NullPointerException: Attempt to write to field 'int android.view.ViewGroup$LayoutParams.height' on a null object reference
java.lang.NullPointerException:尝试写入空对象引用上的字段“int android.view.ViewGroup$LayoutParams.height”
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;
回答by Dmitri Timofti
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:
由于您正在以编程方式创建 Button,b
因此不会设置任何布局参数。所以你需要像这样手动设置它们:
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
b.setLayoutParams(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);