2013-08-29 42 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

添加可繪製的填充值爲一些負值 –

相關問題