2012-07-20 104 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”。