Android Radiobutton Image
I have a radiogroup with custom radiobuttons. Icons are set using rbFirst.setButtonDrawable(R.drawable.first); But icon is not in the center, how do I fix it? I tried different at
Solution 1:
Try using setGravity(Gravity.CENTER);
of setting it as a background drawable.
Or if it does not help you will have to derive a new class from RadioButton and override onDraw().
Here's layout
<?xml version="1.0" encoding="utf-8"?><RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"
><org.test.TestProj.RadioButtonCenterandroid:id="@+id/myview"android:layout_width="fill_parent"android:layout_height="100dp"android:layout_centerInParent="true"android:text="Button test"
/></RelativeLayout>
The code:
package org.test.TestProj;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.RadioButton;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
publicclassRadioButtonCenterextendsRadioButton {
publicRadioButtonCenter(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArraya= context.obtainStyledAttributes(attrs, R.styleable.CompoundButton, 0, 0);
buttonDrawable = a.getDrawable(1);
setButtonDrawable(android.R.color.transparent);
}
Drawable buttonDrawable;
@OverrideprotectedvoidonDraw(Canvas canvas) {
super.onDraw(canvas);
if (buttonDrawable != null) {
buttonDrawable.setState(getDrawableState());
finalintverticalGravity= getGravity() & Gravity.VERTICAL_GRAVITY_MASK;
finalintheight= buttonDrawable.getIntrinsicHeight();
inty=0;
switch (verticalGravity) {
case Gravity.BOTTOM:
y = getHeight() - height;
break;
case Gravity.CENTER_VERTICAL:
y = (getHeight() - height) / 2;
break;
}
intbuttonWidth= buttonDrawable.getIntrinsicWidth();
intbuttonLeft= (getWidth() - buttonWidth) / 2;
buttonDrawable.setBounds(buttonLeft, y, buttonLeft+buttonWidth, y + height);
buttonDrawable.draw(canvas);
}
}
}
Finally, here's an attrs.xml file you need to put in res/values so the code can get at platform-defined attributes.
<?xml version="1.0" encoding="utf-8"?><resources><declare-styleablename="CompoundButton"><attrname="android:button" /></declare-styleable></resources>
Post a Comment for "Android Radiobutton Image"