自定义Checkbox让复选框居中对于RadioButton同样适用

2018-01-12 11:19:07来源:oschina作者:Moster_泞澈人点击

分享
package com.ysd.keepcar.view.shop.model;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.CheckBox;
/**
* Created by 郝悦 on 2018/1/11.
*/
public class MyCustomCheckbox extends CheckBox {
private static final String TAG = MyCustomCheckbox.class.getSimpleName();
public MyCustomCheckbox(Context context) {
super(context);
}
public MyCustomCheckbox(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyCustomCheckbox(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Drawable[] drawables = getCompoundDrawables();
Drawable drawable = drawables[0];
int gravity = getGravity();
int left = 0;
if (gravity == Gravity.CENTER) {
left = ((int) (getWidth() - drawable.getIntrinsicWidth() - getPaint().measureText(getText().toString()))
/ 2);
}
drawable.setBounds(left, 0, left + drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
}
}

布局


android:id="@+id/checkBox"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:button="@null"
android:drawableStart="@drawable/checkbox_selector"
android:gravity="center" />

参考地址:


https://www.jianshu.com/p/3eaae0e223c1

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台