Skip to content Skip to sidebar Skip to footer

Creating A Button In Java, Causes Getlayoutparams To Return Null

I need to create a button in Java. Below is my code: Button b = new Button(MyClass.this); b.requestLayout(); LayoutParams lp = b.getLayoutParams(); lp.height = LayoutParams.WRA

Solution 1:

You have to add this button to a view if you want to get LayoutParams from button. Or just create new LayoutParams and set it.

Solution 2:

It's returning null because when you programmatically create a widget, it has no layout params! (Until you add it to a view, then it receives defaults from the LayoutManager)

edit: above is referring to line 3 of your code

Set them like this:

TextViewmoneyTV=newTextView(this);
LayoutParamslp1=newLayoutParams(HeightParamHere, WidthParamHere, WeightParamHere);
moneyTV.setLayoutParams(lp1);

Edit2: here's some readybake replacement code.

Buttonb=newButton(MyClass.this);
b.setLayoutParams(newLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
b.setText("bla");
b.setTextSize(16);
b.setOnClickListener(myListener);

Assuming you have defined myListener, this should work.

Solution 3:

Because I'm adding this button via ListView::addFooterView, it turns out I had to use the ListView type.

 b.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.WRAP_CONTENT, ListView.LayoutParams.WRAP_CONTENT));

Using this instead of just LayoutParams resolves my crash. Hope this helps others.

Post a Comment for "Creating A Button In Java, Causes Getlayoutparams To Return Null"