user2121620
user2121620

Reputation: 676

Android - button disappears when resized

I am trying to have a button which scales dynamically. At run time, I want its width and height to be 70% of the current size. However, the button is disappearing. Here is my code:

    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);

And the 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"

    />

Upvotes: 0

Views: 140

Answers (1)

dberm22
dberm22

Reputation: 3203

EDIT:

Ahh...it is because you are not casting the right thing as an int. You are casting 0.7 as an int (which goes to zero) and then multiplying it, instead of multiplying and then casting. You can use (int) (.7 * width) instead of (int) .7 * width.

See my example: http://ideone.com/NSGwGF

Anyway, my advice below still stands.


Why not use:

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

instead of:

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

Upvotes: 1

Related Questions