简体   繁体   中英

“Distribute weights evenly” in code

I have one little problem...Here is my code..Is there a way to "distribute weights evenly" for those buttons what I made.. I tried to button[i].setWidth() .. but when I turn around my phone it looks ugly.. so Is there away to distribute buttons width auto?

    ViewGroup row1 = (ViewGroup)findViewById(R.id.TableRow02);
    ViewGroup row2 = (ViewGroup)findViewById(R.id.TableRow04);
    ViewGroup row3 = (ViewGroup)findViewById(R.id.TableRow06);
    ViewGroup row4 = (ViewGroup)findViewById(R.id.TableRow08);
    ViewGroup row5 = (ViewGroup)findViewById(R.id.TableRow10);

    Button button[] = new Button[36];
    for(int i=1;i<36;i++)
    {
        button[i] = new Button(this);

        if(i==32||i==33||i==34||i==35){button[i].setVisibility(-1);}

        button[i].setText("700€");
        button[i].setTextSize(10);
        button[i].setWidth(20);

     // Insert buttons in rows
        if(i<8){row1.addView(button[i]);}
        else if(i<15){row2.addView(button[i]);}
        else if(i<22){row3.addView(button[i]);}
        else if(i<29){row4.addView(button[i]);}
        else if(i<36){row5.addView(button[i]);}
    }

Tactically, put the buttons in a LinearLayout and set android:layout_weight="1" for each of them.

Strategically, design a decent UI, one that does not involve a row of 36 buttons.

As CommonsWare said, instead of setting the width, you should consider to set the weight parameter of the buttons in order to achieve a flexible layout.

If you want to achieve this programmatically (ie in code and not in the XML layout), you can use the button's setLayoutParams method. I haven't tested it, but something like this should work:

// outside of loop
LayoutParams p = new LinearLayout.LayoutParams(
    LayoutParams.MATCH_PARENT, 
    LayoutParams.MATCH_PARENT, 
    1.0
);

....
// enter loop
....

button[i].setLayoutParams(p);

In this example, 1.0 represents the weight. The other two parameters represent layout_width and layout_height parameter.

But seriously, I can't imagine that a layout with 36 buttons is very user friendly:-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM