Dynamically change button width in Android

My question is very simple, I am trying to dynamically change the width of this button:

Button> android: layout_height = "35dip" android: background = "@ drawable / buttonlesson" android: text = "Level 3 [TAP HERE]" android: onClick = "MenuLI1L3" android: layout_width = "300dp" android: ID = " @ + identifier / II 3 "> / Button"

Here is the code I'm using:

 Button myButton = (Button) findViewById(R.id.II3);
 myButton.setWidth(10);
 myButton.setText("kl");

The text does change, but not the width. It sounds like there is a mistake. There is another button on the right panel that allows you to fill in the gap when this button is reduced to 10 pixels, so I also can’t change the Linringayout.

Any explanations and solutions? shouldn't it work? thank

+5
source share
2 answers

As a suggestion, try calling invalidate () on the parent view (which will cause the drawing calls to all children, including your button). This may not work, because you will also need to restart its onMeasure () logic (which runs before drawing).

Playback using an invalid or any other method that causes the parent to invoke onMeasure for children.

0
source

I assume wrap_content does not work for yours in your particular case, right? If you need absolute width, you need to assign this via new LayoutParameters, i.e.

myButton.setLayoutParams(new LinearLayout.LayoutParams(
    30 * someDensityFactor, LinearLayout.LayoutParams.WRAP_CONTENT
))

someDensityFactor - (float). , , .

+2

All Articles