我正在创建一个自定义数字选择器,当我将它设置为垂直时,一切看起来都很好,但是当我将它设置为水平时,元素不对齐。
按钮上有一些文字,然后我添加了一张图片。
没有加号和减号按钮:
带按钮
这是我的代码:
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);
}