import android.app.Activity;
import android.os.Bundle;
/**
* 最近在做底部导航栏的过程中发现使用RadioGroup中嵌套RadioButton的方式
* 无法让RadioButton的图片居中显示,如下是代码
* 下面是运行图片,可以看到设置了drawableTop后的图片不管你怎么设置,它都无法垂直居中显示
* 看了RadioButton内部的实现,才发现原因如下,RadioButton是继承于TextView的,也就是说其实
* RadioButton设置drawableTop其实就是原来的TextView设置TextView设置drawableTop
* 那么看下TextView是对该属性如何处理的
* 从TextView的onDraw()方法可以看出:
* // IMPORTANT: The coordinates computed are also used in invalidateDrawable()
* // Make sure to update invalidateDrawable() when changing this code.
* if (dr.mShowing[Drawables.TOP] != null) {
* canvas.save();
* canvas.translate(scrollX + compoundPaddingLeft +
* (hspace - dr.mDrawableWidthTop) / 2, scrollY + mPaddingTop);
* dr.mShowing[Drawables.TOP].draw(canvas);
* canvas.restore();
* }
* 其实该代码片段就是绘制drawableTop的逻辑,可以看出drawableTop是就于控件顶部位置开始绘制的,
* 此时的y坐标是scrollY + mPaddingTop。从这段代码我们可以找到让RadioButton设置图片居中显示的方案
* 简单的说,就是给该drawable设置一个合适的paddingTop就解决问题,至于设置多少呢,那么我们就在RadioButton
* 在测量自身大小的时候来实现,代码如下
*/
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioGroup
android:id="@+id/rooter_bar_action"
android:layout_centerVertical="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/white"
android:orientation="horizontal"
android:visibility="visible">
<RadioButtonCenter
style="@style/gallery_tab_bottom"
android:checked="true"
android:drawableTop="@mipmap/ic_launcher" />
<RadioButtonCenter
style="@style/gallery_tab_bottom"
android:drawableTop="@mipmap/ic_launcher" />
<RadioButtonCenter
style="@style/gallery_tab_bottom"
android:drawableTop="@mipmap/ic_launcher" />
</RadioGroup>
</RelativeLayout>
图片如下显示:
自定义后的radiobutton代码如下:、
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.RadioButton;
public class RadioButtonCenter extends RadioButton {
public RadioButtonCenter(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 拿到真实图片的高度,用控件的测量高度减去真实高度/2就是
// padding值,将该padding值设置给topPadding就行了,其它padding保持正常的值
Drawable[] drawables = getCompoundDrawables();
Drawable topDrawable = drawables[1];
if (topDrawable != null) {
int padding = (getMeasuredHeight() - topDrawable.getBounds().height()) / 2;
setPadding(getPaddingLeft(), padding, getPaddingRight(), getPaddingBottom());
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
}