如何添加光标并激活我的editText?

时间:2015-07-08 11:36:59

标签: android android-activity android-edittext cursor

实际上我在Android应用程序中创建了一个自定义 EditText。 我所做的是我创建了一个名为CustomEditText的类,我正在绘制我的EditText。其代码如下:

public class CustomEditText extends View {

String mText;
Context mContext;
Paint paint = new Paint();

public CustomEditText(Context context) {
    super(context);
    mContext = context;
    paint.setColor(Color.WHITE); // You could setup the background etc here
    paint.setStyle(Style.FILL);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    drawTextOnCanvas(canvas, mText);
}

private void drawTextOnCanvas(final Canvas canvas, String mText) {
    canvas.drawPaint(paint);

    final EditText editText = new EditText(mContext);
    editText.setTextColor(BLACK);
    editText.setEnabled(true);

    editText.setDrawingCacheEnabled(true);
    editText.measure(MeasureSpec.makeMeasureSpec(canvas.getWidth(), MeasureSpec.EXACTLY), 50);

    editText.layout(0, 0, editText.getMeasuredWidth(), editText.getMeasuredHeight());

    canvas.drawBitmap(editText.getDrawingCache(), 0, 0, paint);
    editText.setDrawingCacheEnabled(false);
}

使用以下代码在MainActivity中调用此类:

    CustomEditText editText = new CustomEditText(this);
    setContentView(editText);

接下来我应该做些什么来添加光标并使此 CustomEditText 像普通 editText 一样(这意味着它应该能够接受选择清除输入文字。)

1 个答案:

答案 0 :(得分:2)

如果您的drawTextOnCanvas()工作正常,只需让CustomEditText延长EditText即可。 (而不是view

如果我理解你的评论,你只需要这样做:

public class CustomEditText extends EditText {

   Context mContext;
   Paint paint;
   EditText editText;


   @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
   public CustomEditText(Context context) {
      super(context);
      paint = new Paint();
      editText = new EditText(context);
      mContext = context;
      paint.setColor(Color.GREEN); 
      paint.setStyle(Paint.Style.FILL);

  }

  @Override
  protected void onDraw(Canvas canvas) {
     canvas.drawPaint(paint);
     super.onDraw(canvas);
  }
}