【问题标题】:How to set a button's parameters programmatically如何以编程方式设置按钮的参数
【发布时间】:2011-12-28 23:41:38
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    使用以下代码设置您的属性:

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

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

    button.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 32);
    

    【讨论】:

    • 我遇到了重力问题。 setGravity( Gravity.CENTER_HORIZONTAL ) 与 xml 文件中的 android:layout_gravity="center_horizo​​ntal" 不同。 xml 文件按钮居中,但不是使用 setGravity() 创建的按钮。
    • 用布局参数试试这个:LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL);
    • 或者在初始化参数调用后:params.gravity = Gravity.CENTER_HORIZONTAL;
    • setGravity 不能按你想要的方式工作的原因是 android:gravity 与 android:layout_gravity 不同
    • 谢谢,但我想通了。我没有在每个按钮上设置 layout_gravity,而是在父视图 LinearLayout 上设置重力。
    【解决方案2】:

    LayoutParams 与包含视图的父 ViewGroup 相关。因此,在您的情况下,它是LinearLayout,因此您需要为该参数创建参数。这就是我要说的:

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    lp.weight = 1f;
    
    Button button = new Button(this);
    button.setLayoutParams(lp);
    button.setText("" + i);
    ((LinearLayout)dialog.findViewById(R.id.Buttons)).addView(button);
    

    【讨论】:

      【解决方案3】:

      将 LayoutParams 用于高度、宽度和重力与

      LinearLayout.LayoutParams (int width, int height)
      

      您可以在哪里使用 WRAP_CONTENT 作为整数。

      然后有Button.setGravity()Button.setTextSize() 用于最后两个。

      希望这会有所帮助。

      【讨论】:

      • 如何使用 Button.setTextSize() 指定倾角?
      • public void setTextSize (int unit, float size);其中单位是“COMPLEX_UNIT_DIP”,大小 = 文本大小。
      【解决方案4】:

      您将使用LayoutParams 对象进行布局设置,并使用Button 类中的setTextSize() 设置文本大小。

      您也可以使用setGravity() 设置重力。

      【讨论】:

        【解决方案5】:

        TextSize 不在布局参数中。要设置 textSize 你必须

        button.setTextSize(32);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-02-24
          • 1970-01-01
          • 2014-09-20
          • 2014-09-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多