1

I have a few buttons with different text length. I'd like to make all buttons equal to the button with the longest text. Their width is

android:layout_width="wrap_content"

So the buttons have different width.

I tried

      int width=button1.getWidth();
      button2.setWidth(width)

But they don't match each other. The width of button2 is different. GetWidth gets I don't know what. SetWidth sets pixels.

I don't want to use weight, because no guarantee that the text of button will be as one line text. I don't want to set exact width of buttons, because there will be extra space on the left and on the right from button's text.

Any ideas please? Thanks!

Niaz
  • 545
  • 2
  • 12
  • 21
  • try to set specific width for both buttons for different density's screen try to use different `dimen` folder. – Kaushik Aug 19 '14 at 15:46
  • Is the pasted code within **oncreate()** or **oncreateview()**. If it's in oncreate then move it to oncrewreview, that will fix your problem – Psypher Aug 19 '14 at 16:11
  • Sorry, not understood. As I wrote I'd like the width is equal for button with maximum text – Niaz Aug 19 '14 at 16:18
  • Ranjith, yes, the code within onCreate(). If I move it to onCreateView, will it fix the problem with different values for getWidth and setWidth? I have to research how to use this onCreateView... – Niaz Aug 19 '14 at 16:24
  • Can't understand onCreateView. Looks like a headache, because I show a few pages inside of one Activity.... – Niaz Aug 19 '14 at 16:34
  • Could you make a JSFiddle please? – Blubberguy22 Aug 19 '14 at 17:21
  • Ranjith, could you please write an example code of how I should use onCreateView(). Thanks – Niaz Aug 20 '14 at 03:59

2 Answers2

0
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true" >

    <Button
        android:id="@+id/button1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="Button is clickble" />

    <Button
        android:id="@+id/button2"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="Button" />

</LinearLayout>

Try this. Use weight in linear layout.

Jossy Paul
  • 1,267
  • 14
  • 26
  • My buttons disappeared from the screen. Maybe width weights are not supported for vertical layout – Niaz Aug 19 '14 at 16:17
0

You are probably calling the getWidth() method too early, because if the UI hasn't finished loading and scaling yet, getWidth() will return an unwanted value.

Try logging the value of getWidth(). If it's zero, it's probably a duplicate of getWidth() and getHeight() of View returns 0

Community
  • 1
  • 1
Blubberguy22
  • 1,344
  • 1
  • 17
  • 29