Drawing multiple lines in edittext e.g. notepad

后端 未结 4 1700
不思量自难忘°
不思量自难忘° 2020-11-27 19:43

I was taking a look at the notepad sample in the android SDK see here: http://developer.android.com/resources/samples/NotePad/src/com/example/android/notepad/NoteEditor.html

4条回答
  •  醉梦人生
    2020-11-27 20:41

    This is the code, based on jkhouws1's suggestion and google's note editor

    public class LinedEditText extends EditText {
        private Rect mRect;
        private Paint mPaint;
    
        // we need this constructor for LayoutInflater
        public LinedEditText(Context context, AttributeSet attrs) {
            super(context, attrs);
    
            mRect = new Rect();
            mPaint = new Paint();
            mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
            mPaint.setColor(R.color.edit_note_line); //SET YOUR OWN COLOR HERE
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            //int count = getLineCount();
    
            int height = getHeight();
            int line_height = getLineHeight();
    
            int count = height / line_height;
    
            if (getLineCount() > count)
                count = getLineCount();//for long text with scrolling
    
            Rect r = mRect;
            Paint paint = mPaint;
            int baseline = getLineBounds(0, r);//first line
    
            for (int i = 0; i < count; i++) {
    
                canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
                baseline += getLineHeight();//next line
            }
    
            super.onDraw(canvas);
        }
    }
    

    In Eclipse IDE press Ctrl+Shift+O to add all needed imports

提交回复
热议问题