向TableLayout的最后一行添加一个按钮

时间:2014-06-04 06:41:48

标签: android android-layout android-button

我已在TableLayout以编程方式TableRow添加了按钮。每行应包括三个按钮。如果按钮数是三的倍数,则没有问题。所有按钮都放置相同的尺寸。但是,最后一行的按钮数量少于三个,其大小与其他按钮不匹配。

这是我的代码:

tableView.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams
                .MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));

 scrollView.setLayoutParams(new ScrollView.LayoutParams(ScrollView.LayoutParams
                .MATCH_PARENT, ScrollView.LayoutParams.WRAP_CONTENT,1));

TableLayout.LayoutParams layoutParams =  new TableLayout.LayoutParams
(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT,1);
        layoutParams.setMargins(0,20,0,20);
int numberOfButtonsForLastRow = masalar.size() - numberOfRows*3;
for (int i = 0; i < numberOfRows; i++) 
{
     tr = new TableRow(fragmentView.getContext());
     tr.setLayoutParams(layoutParams);
     for (int j= 0;j<3;j++)
     {
         btn = new Button(getActivity());
         btn.setBackgroundResource(R.drawable.buttonstyle);
         btn.setText(masalar.get(masaCounter));
         TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams
         .MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT, 1);
         params.setMargins(20, 0, 20, 0);
         btn.setLayoutParams(params);
         btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

             }
          });
        tr.addView(btn);
        masaCounter++;
    }
    tableView.addView(tr);
}
if(numberOfButtonsForLastRow>0)
{
    tr = new TableRow(fragmentView.getContext());
    tr.setLayoutParams(layoutParams);
    for (int j= 0;j<numberOfButtonsForLastRow;j++)
    {
       btn = new Button(getActivity());
       btn.setBackgroundResource(R.drawable.buttonstyle);
       btn.setText(masalar.get(masaCounter));
       TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams
        .MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT);
       params.setMargins(20, 0, 20, 0);
       btn.setLayoutParams(params);
       btn.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {

              }
         });
       tr.addView(btn);
       masaCounter++;
     }
     tableView.addView(tr);
 }

这是最后一个按钮的样子。我希望它与其他人一样大小。我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

TableRow.LayoutParams中添加与前2行相同的布局权重,以便将按钮划分为TableView

TableRow.LayoutParams params = new TableRow.LayoutParams(btn.getWidth(), btn.getHeight());

答案 1 :(得分:0)

你需要重量,你在(0 ... 1)

之间划出一行的空间
TableLayout.LayoutParams rows = new     
    TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, 0, 
    1.0f / (float) NUMBUTTONS);

row.setLayoutParams(rows););