0

我尝试创建动态 linerlayout 并创建了两个按钮。

LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.HORIZONTAL);
        layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.FILL_PARENT));

        TextView titleView = new TextView(this);
        titleView.setWidth(LayoutParams.WRAP_CONTENT);
        titleView.setHeight(LayoutParams.WRAP_CONTENT);
        titleView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        titleView.setText("Hallo Welt!");
        layout.addView(titleView);

        Button btnConnect = new Button(this);
        btnConnect.setText("Connect");
        layout.addView(btnConnect);

        Button btnDisconnect = new Button(this);
        btnDisconnect.setText("Disconnect");
        layout.addView(btnDisconnect);

我想把连接按钮放在左角,想把断开按钮放在右上角。我怎样才能做到这一点?

4

2 回答 2

1

您是否尝试为按钮设置布局重力?

LayoutParams params;

Button btnConnect = new Button(this);
params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.Left;
btnConnect.setLayoutParams(params);
...
Button btnDisconnect = new Button(this);
params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.Right;
btnConnect.setLayoutParams(params);
...

布局重力定义了在其父视图中放置视图的位置(也请参阅Android 上的 Gravity 和 layout_gravity

干杯

于 2013-03-04T14:19:37.513 回答
1

您可以使用 RelativeLayout 而不是线性布局。

并将规则添加到 RelativeLayout.Layoutparams 的布局参数 params = RelativeLayout.Layoutparams params = (RelativeLayout.LayoutParams)button.getLayoutParams(); params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

于 2013-03-04T14:20:48.757 回答