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); } }
RightDrawableCenterTextView
最新推荐文章于 2024-06-16 09:38:27 发布