lhlhiuy 2015-04-08 14:25 采纳率: 0%
浏览 3489

如何在动态添加tablerow并且在tablerow中循环添加按钮

package com.sxu.cs.tracelife;

import android.os.Bundle;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.view.Gravity;
import android.view.Menu;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.TableLayout;
import android.widget.TableRow;

public class MainActivity extends Activity {

TableLayout tableLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tableLayout = (TableLayout) findViewById(R.id.life_table);
for(int i = 0;i<30;i++){
TableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
for(int j = 0;j<30;j++){
Button bn = new Button(this);
bn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
bn.setText("1");
tr.addView(bn);
}
tableLayout.addView(tr);
}
}
}

请大神帮忙看一下这段代码哪出问题了,总是一个tablelayout 没有加进去tablerow

  • 写回答

1条回答 默认 最新

  • danielinbiti 2015-04-08 14:59
    关注

    看着应该是LayoutParams乱了,你这里默认都是ActionBar.LayoutParams,那不对。
    TableRow的LayoutParams应该是TableRow.LayoutParams

     bn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
     像这行,应该
     bn.setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
    
    
     tr.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
     需要 
     tr.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
    
    评论

报告相同问题?