Search code examples
androidandroid-layoutandroid-edittextunderline

How to add pagelines to a EditText in android?


Is it possible to show pagelines in a EditText?

I mean these lines:

enter image description here

Let's say my EditText is 500 by 500 pixels in size. I want those lines to be visible across that 500 by 500 square.

Is there a build in way to do this? I already tried Google but I couldn't find an answer. I guess my other option is to dynamically create a graphic based on the textheight and linespacing, such an ugly work-around.


Solution

  • 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);
        }
    }