【Androidアプリ開発】TableLayoutでボタンを動的生成し均等に配置したい時のポイント

この記事は約4分で読めます。

xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false"
    android:orientation="vertical">

    <TableLayout
        android:id="@+id/TableLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
          android:layout_centerHorizontal="true"
        android:layout_margin="10dp"
        android:shrinkColumns="1,2,3"
        android:stretchColumns="1,2,3" />

</RelativeLayout>

Java


public class D_Test1_Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.d_test1);

     :
     :

        initTableLayout();

    }

    private void initTableLayout() {

     :
     :

        TableLayout tableLayout = findViewById(R.id.TableLayout1);

        TableRow tableRow1 = new TableRow(this);
        tableLayout.addView(tableRow1);
        tableRow1.addView(createButton(shuf_data3.get(0), 1));
        tableRow1.addView(createButton(shuf_data3.get(1), 2));
        tableRow1.addView(createButton(shuf_data3.get(2), 3));

        TableRow tableRow2 = new TableRow(this);
        tableLayout.addView(tableRow2);
        tableRow2.addView(createButton(shuf_data3.get(3), 4));
        tableRow2.addView(createButton(shuf_data3.get(4), 5));
        tableRow2.addView(createButton(shuf_data3.get(5), 6));

     :
     :

    }

    private Button createButton(String text, int btn_cnt) {
        Button button = new Button(this);
        button.setText(text);
        button.setTextSize(24.0f);

        TableRow.LayoutParams buttonLayoutParams = new TableRow.LayoutParams(
                0, TableRow.LayoutParams.MATCH_PARENT, 1);

     :
     :


タイトルとURLをコピーしました