0

在android中,如何使用java插入线性布局,并在水平布局中有三个按钮,并使按钮居中。

所以基本上我想要一个具有三列和 1 行的水平线性布局,每列具有相同的宽度,并在每个布局单元格中插入一个垂直和水平居中的图像按钮。

    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.HORIZONTAL);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
    layout.setLayoutParams(params);

有谁知道如何做到这一点?

谢谢。

4

2 回答 2

1

您可以对线性布局使用 weightsum = 3,对每个按钮使用 layout_weight = 1。查看详细代码。我希望这将有所帮助。祝你好运 :)

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.HORIZONTAL);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    layout.setLayoutParams(params);

    layout.setWeightSum(3);

    for (int i = 0; i < 3; i++) {
        LinearLayout.LayoutParams btnParams = new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        btnParams.weight = 1.0f;

        Button btn = new Button(this);
        btn.setText("Btn");
        btn.setLayoutParams(btnParams);

        layout.addView(btn);
    }

    setContentView(layout);
    }
}

或者这个代码更好但更复杂^^

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LinearLayout mainLayout = new LinearLayout(this);
    mainLayout.setOrientation(LinearLayout.HORIZONTAL);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    mainLayout.setLayoutParams(params);

    mainLayout.setWeightSum(3);

    for (int i = 0; i < 3; i++) {
        LinearLayout.LayoutParams btnParams = new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

        Button btn = new Button(this);
        btn.setText("Btn");
        btn.setLayoutParams(btnParams);

        LinearLayout childLayout = new LinearLayout(this);
        LinearLayout.LayoutParams childParam = new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        childParam.weight = 1.0f;

        childLayout.setLayoutParams(childParam);
        childLayout.setGravity(Gravity.CENTER);
        childLayout.addView(btn);

        mainLayout.addView(childLayout);
    }

    setContentView(mainLayout);
}
}
于 2013-08-03T20:14:21.903 回答
1

您可以通过将布局的重力设置为水平居中来使布局中的所有子视图居中,例如:

LayoutParams layout_params = new LinearLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT, Gravity.CENTER_HORIZONTAL);

然后是带有新构建的 LayoutParams 的 addView

于 2013-08-03T19:37:15.557 回答