【问题标题】:Buttons with images don't align in horizontal linear layout带有图像的按钮在水平线性布局中不对齐
【发布时间】:2012-07-19 10:38:57
【问题描述】:

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

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

带按钮

这是我的代码:

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

 }

我该如何解决这个问题? 谢谢 :)

//编辑

我已经这样解决了:

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

【问题讨论】:

    标签: android android-linearlayout alignment


    【解决方案1】:

    尝试使用 android:layout_gravity="center_vertical" 设置您的元素。

    【讨论】:

      【解决方案2】:

      在初始化 LayoutParams 后试试这个:

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

      那么,就按照你现在的方式绑定吧。

      【讨论】:

        猜你喜欢
        • 2016-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-05
        • 2012-09-27
        • 1970-01-01
        • 1970-01-01
        • 2015-08-11
        相关资源
        最近更新 更多