2013-11-21 62 views
0

我正在自定義Edittext。下面是代碼: -自定義Edittext使用onDraw和光標位置不匹配?

package com.wysiwyg.main; 

import android.content.Context; 
import android.graphics.Canvas; 
import android.graphics.Color; 
import android.graphics.Paint; 
import android.graphics.Rect; 
import android.util.AttributeSet; 
import android.widget.EditText; 

public class LineEditText extends EditText { 
    private Rect mRect; 
    private Paint mPaint; 

    // we need this constructor for LayoutInflater 
    public LineEditText(Context context, AttributeSet attrs) { 
     super(context, attrs); 

     mRect = new Rect(); 
     mPaint = new Paint(); 
     mPaint.setStyle(Paint.Style.FILL_AND_STROKE); 
     mPaint.setColor(Color.BLUE); //SET YOUR OWN COLOR HERE 
     setMinLines(15); 
    } 

    @Override 
    protected void onDraw(Canvas canvas) { 
     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); 

     for (int i = 0; i < count; i++) { 

      canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint); 
      baseline += getLineHeight()+10;//next line 
     } 

     // Finishes up by calling the parent method 
     super.onDraw(canvas); 
    } 
} 

現在這條線baseline += getLineHeight()+10;//next line,畫下一條線的線之上的特定空間。現在光標位置不會相對於該行移動。如果我按Enter鍵,那麼光標首先出現在該行的上方,然後我按下Enter鍵,它就進入行間。

我希望你明白我的意思。

+0

你想實現什麼?你想在行之間設置空格嗎? –

+0

我可以實現線條之間的空間。問題是,在達到空間後,光標位置不在線上。它在線之間 –

回答

0

嘗試這種方式

public class MyEditText extends EditText { 


    public MyEditText(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     init(context); 
    } 

    public MyEditText(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     init(context); 
    } 

    public MyEditText(Context context) { 
     super(context); 
     init(context); 
    } 

    private void init(Context mContext) { 
     setLineSpacing(2, 1); // You can set here as your requirement 
    } 


}