在记事本EditText android中实时字符数

时间:2014-12-02 09:47:36

标签: android android-edittext counter notepad

我有一个自定义EditText,看起来像记事本。在那里我需要显示实时字符数 任何人都可以帮助我开始。

LineEditText.java

public class LinedEditText extends EditText {
    private Rect mRect;
    private Paint mPaint;
    int initialCount=10
    @SuppressLint("NewApi")
    public LinedEditText(Context context, AttributeSet attrs) {
        super(context, attrs);

    mRect = new Rect();
    mPaint = new Paint();
    mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
    mPaint.setColor(Color.parseColor("#C0C0C0")); //SET YOUR OWN COLOR HERE
   /*initialCount=getMinLines();
    setLines(initialCount);*/
}

@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();//for long text with scrolling

    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);
}

}

xml layout

<com.rb.lined.edittext.LinedEditText
                android:id="@+id/edit_story"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"                
                android:background="@null"
                android:inputType="textMultiLine|textNoSuggestions"
                android:minLines="5"
                android:singleLine="false"
                android:imeOptions="actionNone"
                android:text="" 
                android:textSize="13sp"
                android:gravity="top|left"
                android:layout_below="@+id/txt_story"
                app:typeface="roboto_condensed"
                android:maxLength="180"/>

2 个答案:

答案 0 :(得分:0)

您可以在EditText上使用 TextWatcher 对象。它被指定为值更改侦听器。

Android Developer - TextView @ addTextChangedListener

Android Developer - TextWatcher

答案 1 :(得分:0)

由于您使用的是自定义视图,因此只需多次调用onDraw即可,您只需绘制字符数。做类似的事情:

canvas.drawText (getText().toString().length(), positionx, positiony, textPaint);

修改

x,y将是yout文本的来源,所以如果你这样做:

Paint myPaint = new Paint();
myPaint.setColor(Color.WHITE);
myPaint.setTextAlign(Paint.Align.CENTER);

positionx = getWidth()/2;
positiony = getHeight()/2;

canvas.drawText (getText().toString().length(), positionx, positiony, textPaint);

这将在您的视图中心显示您的文字。