2013-08-03 85 views
0

在android中,如何使用java插入線性佈局,並且在水平佈局中有三個按鈕,並使按鈕居中。如何在android中創建線性佈局和中心按鈕?

所以基本上我想與三列和第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); 

有沒有人知道如何做到這一點?

謝謝。

回答

1

您可以通過設置重力排列中心佈局中的所有子視圖居中水平,如:

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

隨後addView與新建成的LayoutParams

+0

如何使每個單元具有相同的寬度? – omega

1

您可以使用weightsum = 3 linearlayout和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); 
} 
}