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
<com.ysd.keepcar.view.shop.model.MyCustomCheckbox 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" />
參考地址:canvas
https://www.jianshu.com/p/3eaae0e223c1ide