带图像的按钮在水平线性布局中不对齐

时间:2012-07-20 07:07:10

标签: android android-linearlayout alignment

我正在创建一个自定义数字选择器,当我将其设置为垂直时,一切看起来都很好,但是当我将其设置为水平时,元素不对齐。

按钮上有一些文字,然后我添加了一个图像 没有加号和减号按钮:

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

// EDIT

我已经修好了这个:

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 个答案:

答案 0 :(得分:2)

初始化LayoutParams后尝试此操作:

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

然后,就像现在一样绑定它。

答案 1 :(得分:0)

尝试使用android设置你的元素:layout_gravity =“center_vertical”。

相关问题