【问题标题】:How do you get buttons in Android to stretch/shrink automatically on screen?如何让 Android 中的按钮在屏幕上自动拉伸/收缩?
【发布时间】:2012-06-20 21:41:40
【问题描述】:

XML 代码:

<GridLayout
    android:id="@+id/grid"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_above="@+id/step"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/menu" >
</GridLayout>

上面的代码创建了一个网格,以便对正在创建的按钮进行简单的布局。

Java 代码:

GridLayout grid = (GridLayout)findViewById(R.id.grid);
grid.setColumnCount(10);
grid.setRowCount(10);
cells = new Button[100];
for (int i = 0; i < 100; i++) { 
    cells[i] = new Button(this);

    if (gen.nextInt(3) % radiofill == 0) //[0,3)
        cells[i].setBackgroundColor(Color.WHITE);
    else
        cells[i].setBackgroundColor(Color.BLACK);

    cells[i].setClickable(true);
    cells[i].setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
            v.setBackgroundColor(Color.BLACK);
        }
    });
    grid.addView(cells[i]); 
}

在这段代码中,100 个按钮被创建并添加到一个数组中,该数组最终被添加到 XML 中创建的 GridLayout 中。

所有按钮似乎都按预期创建、放置和工作,但按钮太大,无法放入手机屏幕。如何使按钮完全填充 GridLayout 而不会溢出或溢出?在本例中,创建了 100 个按钮,但程序旨在允许创建多种类型的完美平方数(4、9、16、25、36、49),因此 GridLayout 需要灵活。

【问题讨论】:

    标签: java android xml button grid-layout


    【解决方案1】:

    如果您使用的是 LinearLayout,则可以

    <LinearLayout android:layout_height="wrap_content"
    android:layout_width="0dip"
    android:layout_weight="1" />
    

    【讨论】:

    • 如果我使用线性布局,有没有办法让按钮保持在一个完美的正方形?
    • 是的。一种选择是创建一个自定义视图,并在 onMesaure() 中确保传入平方值。有很多关于这个主题的帖子。
    最近更新 更多