Search code examples
androidandroid-linearlayoutalignment

Buttons with images don't align in horizontal linear layout


I'm creating a custom numberpicker and when I set it to be vertical everything looks fine, but when I set it horizontal, the elements don't align.

The buttons have some text on it, and then I add a image.
Without plus and minus button :

enter image description here

With buttons

enter image description here

This is my code:

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

 }

How can I fix this? thx :)

//EDIT

I have fixed it like this:

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

Solution

  • Try this after you initialize you LayoutParams:

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

    Then, just bind it as you're doing now.