如何以编程方式设置按钮的参数 [英] How to set a button's parameters programmatically

查看:77
本文介绍了如何以编程方式设置按钮的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向这样的布局添加一堆按钮:

I'm trying to add a bunch of buttons to a layout like this:

for( int i = 0; i < 10; i++ ) {
    Button button = new Button( this );
    button.setText( "" + i );
    ( ( LinearLayout )dialog.findViewById( R.id.Buttons ) ).addView( button );
}

我的问题是如何以编程方式对所有按钮执行此操作:

My problem is how do I do this programmatically to all the buttons:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:textSize="32dip" />

我一直在查看LayoutParams,但它看起来并不完整.像我如何将textSize设置为32 dip?

I've been looking at LayoutParams but it doesn't look complete. Like how do I set the textSize to 32 dip?

推荐答案

使用以下代码设置属性:

Set your attributes using the following code:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
button.setLayoutParams(params);
button.setGravity(Gravity.CENTER_HORIZONTAL);
button.setTextSize(32);

如果要指定文本大小单位,请使用:

If you want to specify the text size units use:

button.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 32);

这篇关于如何以编程方式设置按钮的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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