Creating a button in Java, causes getLayoutParams to return null

北慕城南 提交于 2019-12-25 02:11:13

问题


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.WRAP_CONTENT;
 lp.width = LayoutParams.WRAP_CONTENT;
 b.setLayoutParams(lp);
 b.setText("bla");
 b.setTextSize(16);
 b.setOnClickListener(myListener);

I then add this button to the bottom of a ListView:

 getListView().addFooterView(b);

However this crashes, because getLayoutParams returns null.

Even if I create new LayoutParams instead of getLayoutParams, i.e.:

 Button b = new Button(MyClass.this);
 LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
 b.setLayoutParams(lp); 
 b.setText("bla");
 b.setTextSize(16);
 b.setOnClickListener(myListener);

then the application crashes. Without setLayoutParams, it runs fine, but my button is not sized properly.

How can I size my button?


回答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.




回答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:

TextView moneyTV = new TextView(this);
LayoutParams lp1 = new LayoutParams(HeightParamHere, WidthParamHere, WeightParamHere);
moneyTV.setLayoutParams(lp1);

Edit2: here's some readybake replacement code.

Button b = new Button(MyClass.this);
b.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
b.setText("bla");
b.setTextSize(16);
b.setOnClickListener(myListener);

Assuming you have defined myListener, this should work.




回答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.



来源:https://stackoverflow.com/questions/6206787/creating-a-button-in-java-causes-getlayoutparams-to-return-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!