【问题标题】:Unable to set Button width in Android无法在 Android 中设置按钮宽度
【发布时间】:2013-09-23 05:29:08
【问题描述】:

我能够控制高度,但不知何故它对按钮宽度没有任何影响。

    // Table Row for Previous button
    TableRow tableRow1 = new TableRow(this);

    tableRow1.setLayoutParams(new TableRow.LayoutParams(
            TableRow.LayoutParams.WRAP_CONTENT,
            TableRow.LayoutParams.WRAP_CONTENT));
    tableRow1.setPadding(5, 5, 5, 5);

    // Button - Previous
    Button btnPrev = new Button(this);
    btnPrev.setText("< Previous");
    btnPrev.setGravity(Gravity.CENTER);
    btnPrev.setOnClickListener(prevListener);

    tableRow1.addView(btnPrev);

    android.view.ViewGroup.LayoutParams params = btnPrev.getLayoutParams();
    params.height = 20;
    params.width = 60;

    btnPrev.setLayoutParams(params);


    // TextView for Previous button
    TextView textView11 = new TextView(this);
    textView11.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
    textView11.setGravity(Gravity.CENTER_VERTICAL);
    textView11.setGravity(Gravity.RIGHT);
    textView11.setPadding(0, 0, 20, 0);
    textView11.setText("New Entry Form");

    tableRow1.addView(textView11);

    android.view.ViewGroup.LayoutParams params1 = textView11
            .getLayoutParams();
    params1.height = (int) dipHeight;
    textView11.setLayoutParams(params1);

    tableLayout.addView(tableRow1);

我试着在这里和那里改变一些东西,但没有看。

您可以花点时间帮我解决这个问题吗?

【问题讨论】:

  • 请提供xml代码
  • 我更改了 width=300 并且工作正常。你的问题是什么?
  • @Govind:下面给出了很多答案。查看它们并接受/支持对您有帮助的答案。

标签: android button layout user-interface


【解决方案1】:
// replace this code
tableRow1.addView(btnPrev);

android.view.ViewGroup.LayoutParams params = btnPrev.getLayoutParams();
params.height = 20;
params.width = 60;
btnPrev.setLayoutParams(params);

             to
tableRow1.addView(btnPrev,new android.view.ViewGroup.LayoutParams(20,60));

【讨论】:

  • 我按照你的建议做了,按钮现在没有出现。
【解决方案2】:

使用下面的代码设置按钮的宽度和高度

btnPrev.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btnPrev.setwidth(60);
btnPrev.setheight(20);

【讨论】:

  • 这会产生运行时错误:java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.TableRow$LayoutParams
【解决方案3】:

您可以通过两种方式设置按钮宽度:

通过java:

 Button.setWidth(int width);

通过 XML 属性:

<Button android:layout_height="wrap_content"
 android:id="@+id/ButtonPrev" 
 android:layout_below="@id/output" 
 android:text="7" 
 android:minWidth="100dp">
</Button>

属性:android:minWidth 将设置按钮的宽度。

参考:Set width of Button in Android

【讨论】:

  • 我以编程方式执行此操作,因此无法使用 XML。
【解决方案4】:

View.requestLayout()也许你想要什么?

【讨论】:

  • 没听明白,请详细说明。
  • 设置视图的布局参数后,调用请求布局使其工作。
猜你喜欢
  • 1970-01-01
  • 2011-04-25
  • 1970-01-01
  • 1970-01-01
  • 2015-06-24
  • 1970-01-01
  • 1970-01-01
  • 2011-06-08
  • 2013-07-17
相关资源
最近更新 更多