-1

int numberofbutton=x;提供されます。

ループしようとしましたがnumberofbutton、3 で割り切れる必要があるため失敗しました。アルゴリズムを記述できません。

に基づいてnumberofbutton、プログラムで TableRow の 3 つのボタンをループする必要があります。
つまり、 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>
4

1 に答える 1