簡體   English   中英

如何將一個按鈕放在右邊,另一個放在左邊

[英]How to put one buttom right and another left

我嘗試動態創建linerlayout,我創建了兩個buttoms。

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);

我想將Connect按鈕放在左上角,並想將disconnet按鈕放在右上角。 我怎樣才能做到這一點?

您是否嘗試為按鈕設置布局重力?

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

干杯

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

並將規則添加到RelativeLayout.Layoutparams的布局參數params = RelativeLayout.Layoutparams params = (RelativeLayout.LayoutParams)button.getLayoutParams(); params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); RelativeLayout.Layoutparams params = (RelativeLayout.LayoutParams)button.getLayoutParams(); params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM