简体   繁体   中英

How to give width and height to a button in Android?

I'm developing a little Android app with some square buttons created dynamically from Java code. I'm using the Absolute.LayoutParams method to give width and height to them, but I get deprecation warnings.

LayoutParams params = new LayoutParams(width,height, 0, 0);
button.setLayoutParams(params);

I tried this too:

button.setHeight(height);
button.setWidth(width);

But it is not working. There is a third way to do it easily and clean?

Thank you in advance!

i think it will be

LayoutParams params = new LayoutParams(width,height);
button.setLayoutParams(params);

Using an AbsoluteLayout , you need to use AbsoluteLayout.LayoutParams , rather than ViewGroup.LayoutParams .

AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams(width, height, 0, 0);
button.setLayoutParams(params);

Also note that the proper way to set the width and height of a View is to do so via the LayoutParams . See ViewGroup.LayoutParams and View.getLayoutParams() . You shouldn't have to set the width and height manually as you do in your second example.

I strongly suggest, however, that you implement this with a RelativeLayout (or LinearLayout , etc.) instead... AbsoluteLayout is deprecated, and for very good reason. There are so many different Android devices with different sized screens now, AbsoluteLayout just won't work across them all. Never, ever, ever using AbsoluteLayout is always good practice :).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM