-1

I am currently learning android and I am trying to create an array of buttons for my app in the following manner:

 LinearLayout answer_layout = (LinearLayout)findViewById(R.id.answer_layout);
    idCount = answer_layout.getId() + 1000;

   for(int i = 0 ; i<letters.length ; i++)
    {
        Button b = new Button(this);
        b.setText(letters[i]);
        b.setTypeface(null, Typeface.BOLD);
        b.setBackgroundResource(R.drawable.puzzletilebg);
        b.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
        b.setIncludeFontPadding(false);
        b.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        b.setId(idCount + i);
        b.setTag(Integer.valueOf(i));
        bLetters[i] = b;
        answer_layout.addView(b);

    }
}

When i run this code, i am able to get a row of buttons depending on the length value of string. My problem is the buttons appear stretched and when the length value is more than 7, The buttons dont appear. For this problem i tried implementing the method suggested here(How do I programmatically add buttons into layout one by one in several lines?) but i didnt get any result. What parameters do i have to use to make the shape of the buttons as a perfect square and make sure they are of the same size for all screen sizes? My button background drawable size is 50x50.

Community
  • 1
  • 1
nexus
  • 119
  • 13

4 Answers4

0

Instead of LinearLayout use a GridLayout

Aditya Vyas-Lakhan
  • 13,409
  • 16
  • 61
  • 96
Gavriel
  • 18,880
  • 12
  • 68
  • 105
0

If you want a perfect square change

LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));

to

LinearLayout.LayoutParams(50, 50);

And ofc if your linearLayour is horizontal the buttons will dissapear on the edge of the screen. You can use Gridlayout instead of LinearLayout, but if you want something like the LinearLayout i recommend: FlowLayout

example:

enter image description here Last edit: sorry is not AutoFitLayout is FlowLayout i edited the answer;

Solve your problem?

Fabio Venturi Pastor
  • 2,519
  • 3
  • 19
  • 32
0

For the problem with button more than 7 not appear, you could try to wrap your LinearLayout answer_layout in a ScrollView or HorizontalScrollView for horizontal scroll behaviour in the xml file.

And for programmatically change the width and the height of the button, you could try this answer https://stackoverflow.com/a/11294075/1331743 from existing post.

Community
  • 1
  • 1
Hendrik
  • 63
  • 10
0

Try with

b.setWidth(50);
b.setHeight(50);

The numbers are pixels, so maybe you have to convert dp to pixels.

Stefano
  • 3,127
  • 2
  • 27
  • 33