2013-03-04 45 views
0

我嘗試創建動態linerlayout和我創建了兩個buttoms。如何把一個buttom權利和另一個左

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

我希望把連接按鈕左側角球,並希望把disconnet按鈕右側角球。我怎樣才能做到這一點?

回答

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

佈局重力定義在哪裏放置在它的父視圖(參見Gravity and layout_gravity on Android太)

乾杯

1

可以使用,而不是線性佈局RelativeLayout的。

和規則添加到 RelativeLayout.Layoutparams則params的佈局PARAMS = RelativeLayout.Layoutparams params = (RelativeLayout.LayoutParams)button.getLayoutParams(); params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

相關問題