-
-
Save RellikJaeger/3f589c47596ea9dd2c14d8e319778c0d to your computer and use it in GitHub Desktop.
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.widget.*; | |
import android.util.*; | |
import android.content.*; | |
import android.graphics.*; | |
/** | |
* 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.setAntiAlias(true); | |
lpaint.setStyle(Paint.Style.FILL); | |
lpaint.setColor(Color.BLACK); | |
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) { | |
lpaint.setColor(textColor); | |
} | |
public int getLineNumberTextColor() { | |
return lpaint.getColor(); | |
} | |
@Override | |
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()); | |
} | |
super.onDraw(canvas); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment