left drawable alignment with text in android

后端 未结 2 1973
悲哀的现实
悲哀的现实 2021-01-22 04:29

I am new to custom view and didn\'t know much about canvas in android, I wanted to align a left drawable to right side of layout along with the text(whether multiline or not) o

2条回答
  •  遇见更好的自我
    2021-01-22 04:49

    try something like this

    package views;
    
    import android.content.Context;
    import android.content.res.Resources;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.Canvas;
    import android.graphics.Paint;
    import android.graphics.Rect;
    import android.util.AttributeSet;
    import android.widget.TextView;
    
    import com.upsilon.docta.R;
    
    
    public class MyTempView extends TextView {
        public MyTempView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    public MyTempView(Context context) {
        super(context);
    }
    
    @Override
    protected void onDraw(Canvas canvas) {
        //ContextCompat.getColor(mContext, R.color.back_text_color)
        Paint textPaint = getPaint();
        Rect bounds = new Rect();
        textPaint.getTextBounds(getText().toString(), 0, getText().length(), bounds);
        int textWidth = bounds.width();
        Resources res = getResources();
        Bitmap bitmap = BitmapFactory.decodeResource(res, R.drawable.ic_close);
        canvas.drawBitmap(bitmap, 0, getHeight() / 2 - bitmap.getHeight() / 2, textPaint);
        canvas.translate(bitmap.getWidth(), 0);
        super.onDraw(canvas);
    }
    }
    

提交回复
热议问题