Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
implementing an EditText with line number on the left. What is new is: - get/set line number margin gap - set line number visible - set line number color Everything is done in the overridden onDraw() method.
import android.widget.*;
import android.util.*;
import android.content.*;
* the simple implementation of an EditText where each line is numbered on the left
public class LineNumberedEditText extends EditText {
/** whether to set the lines visible or not */
private boolean lineNumberVisible = false;
private Rect _rect;
private Paint lpaint;
/** the gap between the line number and the left margin of the text */
private int lineNumberMarginGap = 2;
*the difference between line text size and the normal text size.
* line text size is preferabl smaller than the normal text size
protected int LINE_NUMBER_TEXTSIZE_GAP = 2;
public LineNumberedEditText (Context context, AttributeSet attrs) {
super(context, attrs);
_rect = new Rect();
lpaint = new Paint();
lpaint.setTextSize(getTextSize() - LINE_NUMBER_TEXTSIZE_GAP);
public void setLineNumberMarginGap(int lineNumberMarginGap) {
this.lineNumberMarginGap = lineNumberMarginGap;
public int getLineNumberMarginGap() {
return lineNumberMarginGap;
public void setLineNumberVisible(boolean lineNumberVisible) {
this.lineNumberVisible = lineNumberVisible;
public boolean isLineNumberVisible() {
return lineNumberVisible;
public void setLineNumberTextColor(int textColor) {
public int getLineNumberTextColor() {
return lpaint.getColor();
protected void onDraw(Canvas canvas) {
// TODO: Implement this method
if (lineNumberVisible) {
//set the size in case it changed after the last update
lpaint.setTextSize(getTextSize() - LINE_NUMBER_TEXTSIZE_GAP);
int baseLine = getBaseline();
String t = "";
for (int i = 0; i < getLineCount(); i++) {
t = "" + (i + 1);
canvas.drawText(t, _rect.left, baseLine, lpaint);
baseLine += getLineHeight();
// set padding again, adjusting only the left padding
setPadding((int)lpaint.measureText(t) + lineNumberMarginGap, getPaddingTop(),
getPaddingRight(), getPaddingBottom());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment