2013-08-29 41 views
1

我有一个单选按钮,需要放在收音机组的中央。以编程方式将单选按钮对齐到收音机组中心

这里是我的代码:

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被放置在中心。

+0

您可以使用无线电集团的重心与中心与右侧或左侧任何你想要的 –

+0

@sunil我试过了,它不会工作 – Goofy

+1

RadioImageButton.setButtonDrawable(图标);不要传递按钮内的图标,而是通过组合可绘制方法传递它,如果任何一个单选按钮它将表现良好。 RadioImageButton.setCompoundDrawablesWithIntrinsicBounds(left,top,right,bottom) –

回答

1

随着TerrilThomas帮助,我能解决这个问题:

这里是解决方案:

RadioImageButton.setButtonDrawable(icon); // Not proper way 

没有通过图标的按钮内,而不是将它传递的复方绘制方法,如果任何一个单选按钮它都会很好。

RadioImageButton.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom)// use this to set the icon

感谢TerrilThomas,欢呼声

+0

感谢您的帖子(y) –

+0

@TerrilThomas现在图标显示在文本的左侧,文本位于中间,但文本和单选按钮之间有很大的空间,如何减少?我还没有设置任何填充,你能建议我的东西 – Goofy

+0

添加可绘制的填充值为一些负值 –

相关问题