I created a custom EditText view in onDraw that is meant to have a red margin line. The problem is that when you scroll down, the line disappears. This code simply draws a margin whos width is pre-defined in the values folder and then colors it with a pre-defined color from colors.xml. Here's my code:
package com.lioncode.notepad;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.EditText;
Public class LinedEditText extends EditText {
private static Paint linePaint;
static {
linePaint = new Paint();
linePaint.setColor(Color.DKGRAY);
linePaint.setStyle(Style.STROKE);
}
public LinedEditText(Context context, AttributeSet attributes) {
super(context, attributes);
init();
}
private Paint marginPaint;
private float margin;
private int paperColor;
private void init() {
Resources myResources = getResources();
marginPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
marginPaint.setColor(myResources.getColor(R.color.notepad_margin));
paperColor = myResources.getColor(R.color.notepad_paper);
margin = myResources.getDimension(R.dimen.notepaper_margin);
}
@Override
protected void onDraw(Canvas canvas) {
Rect bounds = new Rect();
int firstLineY = getLineBounds(0, bounds);
int lineHeight = getLineHeight();
int totalLines = Math.max(getLineCount(), getHeight() / lineHeight);
for (int i = 0; i < totalLines; i++) {
int lineY = firstLineY + i * lineHeight;
canvas.drawLine(bounds.left, lineY, bounds.right, lineY, linePaint);
}
// draw margin
canvas.drawLine(margin, 0, margin, getMeasuredHeight(), marginPaint);
// move the text from along the margin
canvas.save();
canvas.translate(margin, 0);
super.onDraw(canvas);
}
}