我想做一个笔记编辑器。它将有EditText
行。这是我的代码:
LinedEditText.java
public class LinedEditText extends EditText {
private Rect mRect;
private Paint mPaint;
public LinedEditText(Context context) {
super(context);
// TODO Auto-generated constructor stub
mRect = new Rect();
mPaint = new Paint();
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setColor(Color.BLUE); //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();
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);
}
TextEditorActivity.java
public class TextEditorActivity extends Activity {
private LinedEditText text;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.text=new LinedEditText(getApplicationContext());
this.setContentView(text);
}
}
结果:
result http://bekirmavus.com/k-resimler/image/android/device-2012-07-17-222950.png
我犯了什么错误?
...谢谢
答案 0 :(得分:3)
正在从光标位置向下绘制线条。只需将光标的默认位置从垂直居中移动到左上角,使用Gravity:
text.setGravity(Gravity.NO_GRAVITY);
或者默认设置所有LinedEditTexts:
public LinedEditTexts(Context context) {
super(context);
setGravity(Gravity.NO_GRAVITY); // or Gravity.TOP | Gravity.LEFT
...
}