int numberofbutton=x;
将会给予。
我尝试循环但失败了,因为numberofbutton
必须能被 3 整除。我不会编写算法。
基于numberofbutton
,我们必须以编程方式循环 TableRow 中的三个按钮。
我的意思是,如果 numberofbutton 是4,
TableRow[0]->Button Button Button
TableRow[1]->Button
如果是3,
TableRow[0]->Button Button Button
更新:
根据 ZouZou 的回答,代码如下但未解决,因为 tr[] 未定义:
int bn = 9;
if (bn % 3 == 0) {
TableRow[] tr = new TableRow[bn / 3];
for (int i = 1; i <=(bn / 3); i++) {
tr[i] = new TableRow(this);
}
} else {
TableRow[] tr = new TableRow[(bn / 3) + 1];
for (int i = 1; i <=(bn / 3) + 1; i++) {
tr[i] = new TableRow(this);
}
}
Button[] b=new Button[bn];
for(int i=1;i<=bn;i++){
b[i]=new Button(this);
}
int index = -1;
for (int i = 0; i < bn; i++) {
if(i%3==0){
index+=1;
tr[index].addView(b[i]);
}else{
tr[index].addView(b[i]);
}
}
更新:
完整的代码,但为什么它不起作用?:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TableLayout tL = (TableLayout) findViewById(R.id.table);
int bn = 9;
TableRow[] tr = null;
if (bn % 3 == 0) {
tr = new TableRow[bn / 3];
for (int i = 1; i <= (bn / 3); i++) {
tr[i] = new TableRow(this);
}
} else {
tr = new TableRow[(bn / 3) + 1];
for (int i = 1; i <= (bn / 3) + 1; i++) {
tr[i] = new TableRow(this);
}
}
Button[] b=new Button[bn];
for(int i=1;i<=bn;i++){
b[i]=new Button(this);
}
int index = -1;
for (int i = 0; i < bn; i++) {
if(i%3==0){
index+=1;
tr[index].addView(b[i]);
tL.addView(tr[index]);
}else{
tr[index].addView(b[i]);
}
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TableLayout
android:id="@+id/table"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="59dp"
android:layout_marginTop="44dp" >
</TableLayout>
</RelativeLayout>