我有一個單選按鈕,需要放在收音機組的中央。以編程方式將單選按鈕對齊到收音機組中心
這裏是我的代碼:
RadioImageButton RadioImageButton = new RadioImageButton(activity);
RadioImageButton.setGravity(Gravity.CENTER);
RadioImageButton.setId(buttonId);
RadioImageButton.setTextColor(Color.BLACK);
RadioImageButton.setButtonDrawable(icon); // this is where i am replacing the default circle with an image
RadioImageButton.setBackgroundDrawable(drawable);
RadioGroup.LayoutParams radioImageButtonParams = new RadioGroup.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT, 1f);
radioImageButtonParams.setMargins(0, 0, 1, 0);
RadioGroup.addView(RadioImageButton, radioImageButtonParams);
在RadioImageButton類
Drawable image;
public RadioImageButton(Context context) {
super(context);
setButtonDrawable(android.R.color.transparent);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (image != null) {
image.setState(getDrawableState());
final int verticalGravity = getGravity() & Gravity.VERTICAL_GRAVITY_MASK;
final int height = image.getIntrinsicHeight();
int y = 0;
switch (verticalGravity) {
case Gravity.BOTTOM:
y = getHeight() - height;
break;
case Gravity.CENTER_VERTICAL:
y = (getHeight() - height)/2;
break;
}
int buttonWidth = image.getIntrinsicWidth();
int buttonLeft = (getWidth() - buttonWidth)/3;
image.setBounds(buttonLeft, y, buttonLeft + buttonWidth, y + height);
image.draw(canvas);
}
}
目前它是這樣的:
radiobutton ------ text
文本僅放置在中心,但不單選按鈕我想要文本和單選按鈕機器人h被放置在中心。
您可以使用無線電集團的重心與中心與右側或左側任何你想要的 –
@sunil我試過了,它不會工作 – Goofy
RadioImageButton.setButtonDrawable(圖標);不要傳遞按鈕內的圖標,而是通過組合可繪製方法傳遞它,如果任何一個單選按鈕它將表現良好。 RadioImageButton.setCompoundDrawablesWithIntrinsicBounds(left,top,right,bottom) –