萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 動態建立多按鈕網格:DisplayMetrics 計算尺寸與批量監聽實作

需求

依螢幕寬度動態生成 4×4 按鈕網格,每行 4 個,按鈕大小自適應,並批量設定點擊事件區分按鈕索引。

完整實作

public class DynamicButtonActivity extends Activity {
    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 1. 取得螢幕尺寸
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;

        // 2. 建立 RelativeLayout 容器
        RelativeLayout layout = new RelativeLayout(this);

        // 3. 生成 16 個按鈕
        Button[] btns = new Button[16];
        int row = -1;
        for (int i = 0; i < 16; i++) {
            btns[i] = new Button(this);
            btns[i].setId(2000 + i);
            btns[i].setText("按鈕" + i);

            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    (width - 50) / 4, 40); // 寬高

            if (i % 4 == 0) row++;
            lp.leftMargin = 10 + ((width - 50) / 4 + 10) * (i % 4);
            lp.topMargin = 20 + 55 * row;

            layout.addView(btns[i], lp);
        }
        setContentView(layout);

        // 4. 批量設定監聽(利用 Tag 傳遞索引)
        for (int i = 0; i < btns.length; i++) {
            final int idx = i;
            btns[i].setTag(idx);
            btns[i].setOnClickListener(v -> {
                int id = (int) v.getTag();
                Intent intent = new Intent(this, NextActivity.class);
                intent.putExtra("btnIndex", id);
                startActivity(intent);
                finish();
            });
        }
    }
}

關鍵點解析

  • DisplayMetrics 取得螢幕像素寬度,計算按鈕寬度 (width - 間距總和) / 列數。
  • RelativeLayout.LayoutParams 透過 leftMargin/topMargin 定位。
  • 使用 setTag(index) + Lambda 避免匿名內部類捕獲最終值問題。
  • 按鈕 ID 設為 2000+i 避免與系統資源衝突。

進階建議

  • 改用 GridLayout 或 RecyclerView (GridLayoutManager) 更彈性、支援回收複用。
  • 按鈕樣式建議定義於 XML Style,程式碼僅 inflate 或 new Button(context, null, R.style.MyButton)。
copyright © 萬盛學電腦網 all rights reserved