Android - 按钮在调整大小时消失

时间:2014-01-14 17:26:32

标签: android android-view android-ui android-button

我正在尝试一个动态缩放的按钮。在运行时,我希望它的宽度和高度是当前大小的70%。但是,按钮正在消失。这是我的代码:

    Button btn = (Button) v.findViewById(R.id.button_delete_transaction);
    btn.setMinWidth(0);
    btn.setMinHeight(0);

    btn.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
    int width = btn.getMeasuredWidth();
    int height = btn.getMeasuredHeight();

    ViewGroup.LayoutParams params = btn.getLayoutParams();

    params.width = (int) .7 * width;
    params.height = (int) .7 * height;

    btn.setLayoutParams(params);

和xml:

<Button

    android:id="@+id/button_delete_transaction"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:background="@drawable/add_img"
    android:focusable="false"

    />

1 个答案:

答案 0 :(得分:1)

编辑:

啊......这是因为你没有把正确的东西作为一个int。你将0.7作为一个int(它变为零),然后乘以它,而不是乘以然后再转换。您可以使用(int) (.7 * width)代替(int) .7 * width

请参阅我的示例:http://ideone.com/NSGwGF

无论如何,我的建议仍然存在。


为什么不使用:

btn.setWidth((int) Math.round(.7 * width));
btn.setHeight((int) Math.round(.7 * height));

而不是:

ViewGroup.LayoutParams params = btn.getLayoutParams();
params.width = (int) .7 * width;
params.height = (int) .7 * height;
btn.setLayoutParams(params);
相关问题