Vertical line using XML drawable

前端 未结 15 697
无人及你
无人及你 2020-11-27 09:57

I\'m trying to figure out how to define a vertical line (1dp thick) to be used as a drawable.

To make a horizontal one, it\'s pretty straightforward:



        
15条回答
  •  离开以前
    2020-11-27 10:03

    I needed to add my views dynamically/programmatically, so adding an extra view would have been cumbersome. My view height was WRAP_CONTENT, so I couldn't use the rectangle solution. I found a blog-post here about extending TextView, overriding onDraw() and painting in the line, so I implemented that and it works well. See my code below:

    public class NoteTextView extends TextView {
        public NoteTextView(Context context) {
           super(context);
        }
        private Paint paint = new Paint();
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            paint.setColor(Color.parseColor("#F00000FF"));
            paint.setStrokeWidth(0);
            paint.setStyle(Paint.Style.FILL);
            canvas.drawLine(0, 0, 0, getHeight(), paint);
        }
    }
    

    I needed a vertical line on the left, but the drawline parameters are drawLine(startX, startY, stopX, stopY, paint) so you can draw any straight line in any direction across the view. Then in my activity I have NoteTextView note = new NoteTextView(this); Hope this helps.

提交回复
热议问题