How to add pagelines to a EditText in android?

后端 未结 3 2037
隐瞒了意图╮
隐瞒了意图╮ 2021-01-14 14:07

Is it possible to show pagelines in a EditText?

I mean these lines:

\"enter

3条回答
  •  不要未来只要你来
    2021-01-14 14:13

    The notepad application sample from the android dev site shows you how to do this.

    http://developer.android.com/resources/samples/NotePad/index.html

    Looks like this (scroll down for code):

    Notepad

    Most of the relevant code is in this file. Pay attention to the LinedEditText inner class. It is defined within the activity. It draws the lines required.

    Inside the activity onCreate() method, setContentView(R.id.note_editor) is set as the view, it is defined like here

    Snippet extracted from here. Update: Code modified by @Pieter888 to draw lines on the entire EditText control.

    import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.Paint;
    import android.graphics.Rect;
    import android.util.AttributeSet;
    import android.widget.EditText;
    
    public class LinedEditText extends EditText 
    {
        private Rect mRect;
        private Paint mPaint;
    
        public LinedEditText(Context context, AttributeSet attrs) 
        {
            super(context, attrs);
            mRect = new Rect();
            mPaint = new Paint();
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setColor(0xFF000000);
        }
    
        /**
         * This is called to draw the LinedEditText object
         * @param canvas The canvas on which the background is drawn.
         */
        @Override
        protected void onDraw(Canvas canvas) 
        {
            int height = canvas.getHeight();
            int curHeight = 0;
            Rect r = mRect;
            Paint paint = mPaint;
            int baseline = getLineBounds(0, r);
            for (curHeight = baseline + 1; curHeight < height; 
                                                     curHeight += getLineHeight())
            {
                canvas.drawLine(r.left, curHeight, r.right, curHeight, paint);
            }
            super.onDraw(canvas);
        }
    }
    

提交回复
热议问题