public class MainActivity extends Activity {
int i,j;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
LinearLayout layout2 = new LinearLayout(this);
layout2.setOrientation(LinearLayout.HORIZONTAL);
layout2.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
LinearLayout layout1 = new LinearLayout(this);
layout1.setOrientation(LinearLayout.VERTICAL);
layout1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
for(j=0;j<5;j++){
Button myButton = new Button(this);
myButton.setText(""+j);
myButton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
myButton.setTextSize(20);
layout.addView(myButton);
}
layout1.addView(layout);
for(j=5;j<10;j++){
Button myButton = new Button(this);
myButton.setText(""+j);
myButton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
myButton.setTextSize(20);
layout2.addView(myButton);
}
layout1.addView(layout2);
setContentView(layout1);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
以上是我的代码。我能够动态创建两行5列的按钮。但在这里我必须手动创建行的布局(布局,布局2)。我以为我会定义一个linearlayout数组。但是,当我尝试指定setOrientation和setLayoutParams时程序崩溃。 我试过了
layout3[0].setOrientation(LinearLayout.HORIZONTAL);
但程序崩溃了。
答案 0 :(得分:1)
实际上很简单
您需要指定
layout3[i] = new LinearLayout(this);
layout3[i].setOrientation(LinearLayout.HORIZONTAL);
layout3[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
然后它有效。