1

我想做一个笔记编辑器。它将有一条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);
    }

}

结果:

结果 http://bekirmavus.com/k-resimler/image/android/device-2012-07-17-222950.png

我犯了什么错误?

谢谢...

4

1 回答 1

3

这条线是从光标位置向下绘制的。只需使用 Gravity 将光标的默认位置从垂直居中移动到左上角:

text.setGravity(Gravity.NO_GRAVITY);

或者默认为所有 LinedEditTexts 设置它:

public LinedEditTexts(Context context) {
    super(context);
    setGravity(Gravity.NO_GRAVITY); // or Gravity.TOP | Gravity.LEFT
    ...
}
于 2012-07-17T20:02:23.470 回答