RightDrawableCenterTextView

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;

public class RightDrawableCenterTextView extends AppCompatTextView {
    public RightDrawableCenterTextView(@NonNull Context context) {
        this(context, null);
    }

    public RightDrawableCenterTextView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RightDrawableCenterTextView(@NonNull Context context,
                                       @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @SuppressLint("RtlHardcoded")
    private void init() {
        setGravity(Gravity.CENTER | Gravity.RIGHT);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Drawable[] drawables = getCompoundDrawables();
        Drawable drawable = drawables[2];
        if (drawable != null) {
            float textWidth = getPaint().measureText(getText().toString());
            int drawablePadding = getCompoundDrawablePadding();
            int drawableWidth = drawable.getMinimumWidth();
            float bodyWidth = textWidth + drawableWidth + drawablePadding
                    + getPaddingLeft() + getPaddingRight();
            canvas.translate((bodyWidth - getWidth()) / 2, 0);
        }
        super.onDraw(canvas);
    }
}

你可能感兴趣的:(十年程序员的专栏,android,java,开发语言)