Android:动态添加按钮时重新排列按钮

时间:2013-02-14 00:39:56

标签: android android-layout android-button

我的问题用图表更好地解释,但这是一般性的想法:

我正在为布局动态添加按钮。在整个用户交互过程中添加了按钮。如果有一个按钮,我希望它在父母的中心。

|...............[Button 1]...............|

对于两个按钮,我希望它们彼此相邻。

|..........[Button 1][Button 2]..........|

此模式将持续到一定数量的按钮(以便不将它们全部聚集在同一行/行上)。因此,假设每行/每行的最大按钮数为4.因此,对于大于4的任意数量的按钮,我希望它们在以下行/行上均匀分割。所以对于5个按钮,它看起来像这样:

|.....[Button 1][Button 2][Button 3].....|
|..........[Button 4][Button 5]..........|

基本上我希望能够以编程方式布局行/行中的按钮,以便每行包含尽可能相同(或接近相同)的按钮数,因此它们均匀分布。


目前我的按钮以网格格式布局,在调用之前是不可见的,但它看起来很难看。所以它看起来像这样:

|[Button 1][Button 2]....................|

或者,如果有5个按钮,它将如下所示:

|[Button 1][Button 2][Button 3][Button 4]|
|[Button 5]..............................|

这看起来很丑陋/俗气,所以我希望它们能够按照我在顶部解释的方式进行编程。


有可能做我要问的事吗?如果是这样,我将如何去做呢?

1 个答案:

答案 0 :(得分:2)

你可以这样做:

1 /使用RelativeLayout作为根ViewGroup用于所有这些。

2 /对LinearLayout的每一行使用Buttons,将其设置为具有唯一ID,并将RelativeLayout.LayoutParams设置为WRAP_CONTENT的宽度和高度。使用CENTER_HORIZONTAL作为规则,当你添加一行(第2,第3,第4等,即不是第1行)时,另外添加规则BELOW,并使用它应该是的行的id下方。

3 /要确定Button是否适合行,请使用RelativeLayout获取行的宽度和getMeasuredWidth()(在步骤1中)。使用那些可以检查Button是否合适 - 假设它们使用固定宽度。

修改

示例(不包括第3步):

在你的Activity中添加一个成员变量ViewGroup list,然后在Activity.onCreate()中添加:

list = new RelativeLayout(this);
list.setLayoutParams(new FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT));
setContentView(list);

添加添加按钮的方法。

private void addButton(String btnTitle)
{
    // find out how many rows we have in our relative layout  
    int rowCount = list.getChildCount();

    int buttonCount = MY_MAX_BUTTONS_PER_ROW;

    // find out how many buttons are in the last row
    if (rowCount > 0) buttonCount = ((ViewGroup)list.getChildAt(rowCount-1)).getChildCount();

    final ViewGroup row;

    // do we have no rows, or is there no room for another button?
    if (rowCount == 0 || buttonCount >= MY_MAX_BUTTONS_PER_ROW)
    {
        // create a row 
        LinearLayout newRow = new LinearLayout(this);
        newRow.setId(rowCount+1);
        RelativeLayout.LayoutParams rowLP = new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
        rowLP.addRule(CENTER_HORIZONTAL);
        if (rowCount > 0) rowLP.addRule(BELOW, rowCount);

        list.addView(newRow, rowLP);

        rowCount++;  

        row = newRow;
    }
    // .. there's room, so add it to the last row
    else 
    {
        row = (ViewGroup)list.getChildAt(rowCount-1);
    }

    // create one of your buttons
    // ...

    button.setLayoutParams(new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
    row.addView(button);
}
相关问题