创建Java中的一个按钮,使getLayoutParams到返回null [英] Creating a button in Java, causes getLayoutParams to return null

查看:592
本文介绍了创建Java中的一个按钮,使getLayoutParams到返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Java中创建一个按钮。下面是我的code:

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);

我再将此按钮添加到一个ListView的底部:

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

 getListView().addFooterView(b);

不过,这崩溃,因为getLayoutParams返回null。

However this crashes, because getLayoutParams returns null.

就算我创造新的LayoutParams代替getLayoutParams,即:

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);

然后应用程序崩溃。如果没有setLayoutParams,它运行良好,但我的按钮没有正常大小。

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

我怎样才能的大小我的按钮?

How can I size my button?

推荐答案

由于我加入的ListView通过:: addFooterView这个按钮,原来我不得不使用ListView控件的类型。

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));

使用这个,而不是仅仅的LayoutParams解决我的崩溃。希望这可以帮助别人。

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

这篇关于创建Java中的一个按钮,使getLayoutParams到返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆