您好我正在尝试将一些TableRows添加到TableLayout,TableLayout在xml文件中声明,TableRows仅在java代码中实例化。 尽管有一些类似的问题,我无法在我的代码中使用它:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
public class MainActivity extends Activity {
TableLayout tableLayout;
Button[][] buttons =new Button[9][9];
TableRow tableRow[]=new TableRow[9];
TableRow.LayoutParams layoutParams=new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tableLayout = (TableLayout) findViewById(R.id.tablay);
for(int line=0; line<9; line++){
tableRow[line]=new TableRow(this);
tableRow[line].setLayoutParams(layoutParams);
tableRow[line].setVisibility(View.VISIBLE);
}
for(int line=0; line<9; line++){
for(int col=0; col<9; col++){
buttons[line][col]=new Button(this);
buttons[line][col].setText(""+line+col);
buttons[line][col].setLayoutParams(layoutParams);
buttons[line][col].setVisibility(View.VISIBLE);
tableRow[line].addView(buttons[line][col]);
}
}
for(int i=0; i<9; i++){
tableLayout.addView(tableRow[i], new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
}
setContentView(R.layout.activity_main);
}
}
应用程序总是在启动后立即终止,我看不出问题所在。 谢谢你的帮助!
答案 0 :(得分:0)
在super.onCreate(savedInstanceState);
之后移动以下行setContentView(R.layout.activity_main);