I want to add a button programmatically, which LayoutParams should be set too. Unfortunaly the app gives an exception:
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;
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With