Search code examples
androidandroid-layoutalignmentandroid-button

Android align set of buttons programatically in layout


the thing which I want to achieve in my application is to create dynamically a set of buttons with different text size and after that align these view inside a linear layout. Here is a sample of what I want to achieve :

image . Depending on the textsize I want the buttons to be align in a single line, if the last button is bigger than the screen size, it should properly go to the next line.

Any suggestions how can I achieve this or what should I look for, because I know that if I try button.getWidth(); it will return 0 and it won't work.

Thanks for any kind of suggestions!

EDIT

To achieve this you can use a new layout open sources by Google called: FlexboxLayout. You can learn more about it in this post from Android Developers Blog.


Solution

  • You can try the following While adding the buttons you can calculate the how much width till occupied as

    occupiedWidth = button1Width + button2Width + ...
    

    Every button width = textWidth + 2*margin + 2*padding

    You can get your width of the text which you put on the button like

    String buttonText = "<Your Button Text>"
    paint.getTextBounds(buttonText, 0, buttonText.length(), bounds);
    int textWidth = bounds.width();
    

    Add this new button margins and paddings as

    int newWidth = textWidth + buttonMargin*2 + buttonPadding*2;
    

    if the total width is exceeding the screenwidth then move to next row.