2012-07-20 127 views
0

我創建了自定義的numberpicker,當我將它設置爲垂直時,一切看起來都很好,但是當我將它設置爲水平時,這些元素不會對齊。帶圖像的按鈕不對齊的水平線性佈局

按鈕上有一些文字,然後我添加一個圖像。
沒有加號和減號按鈕:

enter image description here

隨着按鈕

enter image description here

這是我的代碼:

private final int ELEMENT_HEIGHT = 50; 
private final int ELEMENT_WIDTH = 65; 

.....

public NumberPicker(Context context, int min, int max,int orientation) { 
    super(context); 

this.setLayoutParams(new LinearLayout.LayoutParams(
      LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
    LayoutParams elementParams = new LinearLayout.LayoutParams(
      ELEMENT_WIDTH, ELEMENT_HEIGHT); 

    // init the individual elements 
    initDecrementButton(context); 
    initValueEditText(context); 
    initIncrementButton(context); 

    this.setOrientation(orientation); 

    if (orientation == VERTICAL) { 
     addView(increment, elementParams); 
     addView(valueText, elementParams); 
     addView(decrement, elementParams); 
    } else { 
     addView(decrement, elementParams); 
     addView(valueText, elementParams); 
     addView(increment, elementParams); 
    } 
} 


private void initIncrementButton(Context context) { 
    increment = new Button(context); 
    increment.setTextSize(15); 
    increment.setText("Max: " + getMaximum()); 
    increment.setCompoundDrawablesWithIntrinsicBounds(null,null , null, context.getResources().getDrawable(R.drawable.plus)); 

} 

private void initDecrementButton(Context context) { 
    decrement = new Button(context); 
    decrement.setTextSize(15); 
    decrement.setText("Min: " + getMinimum()); 
    decrement.setCompoundDrawablesWithIntrinsicBounds(null, context.getResources().getDrawable(R.drawable.minus),null ,null); 

} 

我該如何解決這個問題? THX :)

//編輯

我有固定它像這樣:

if (orientation == VERTICAL) { 
     elementParams.gravity = Gravity.CENTER_HORIZONTAL; 
     addView(increment, elementParams); 
     addView(valueText, elementParams); 
     addView(decrement, elementParams); 
    } else { 
     elementParams.gravity = Gravity.CENTER_VERTICAL; 
     addView(decrement, elementParams); 
     addView(valueText, elementParams); 
     addView(increment, elementParams); 
    } 

回答

2

試試這個之後,你初始化你的LayoutParams:

LayoutParams elementParams = new LinearLayout.LayoutParams(ELEMENT_WIDTH, ELEMENT_HEIGHT); 
elementParams.gravity = Gravity.CENTER_VERTICAL; 

然後,只需綁定它作爲你現在做的事情。

+0

Thx,這工作:) – 2012-07-20 07:23:17

+0

一天的英雄:「) – 2012-10-17 18:40:29

0

嘗試這樣的Android設置你的元素:layout_gravity = 「center_vertical」。