设置不可更改的editText android的某些部分 [英] Set unchangeable some part of editText android

查看:15
本文介绍了设置不可更改的editText android的某些部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些用于手机号码输入的 EditText.应用程序必须为每个国家/地区添加唯一的文本.例如亚美尼亚必须添加 +374 ,用户必须填写其他数字.另外 +374 必须是不可更改的,用户不能更改或删除它.那么有什么方法可以做到这一点吗?

I have some EditText for mobile number input. App must add unique text for every country. For example for Armenia is must add +374 , and user must fill other numbers. Also +374 must be unchangeable, user can't change or remove it. So is there some kind of ways for doing this?

我不想在此文本中使用 textView 或其他视图并将其放在 ediText 的左侧.我想找到一些操作较少的方法.我需要冻结文本而不是检查每个文本更改或在用户删除其中的某些部分时添加丢失的文本.

I don't want to use textView or another view with this text and put it left of the ediText. I want to find some way with less operations. I need text to be frozen not to check every text changes or add missing text when user will delete some part of it.

推荐答案

创建一个自定义可绘制类,帮助将文本转换为可绘制对象.

Create a custom drawable class that will help to convert text into drawable.

public class TextDrawable extends Drawable {

  private final String text;
  private final Paint paint;

  public TextDrawable(String text) {
      this.text = text;
      this.paint = new Paint();
      paint.setColor(Color.BLACK);
      paint.setTextSize(16f);
      paint.setAntiAlias(true);
      paint.setTextAlign(Paint.Align.LEFT);
  }

  @Override
  public void draw(Canvas canvas) {
      canvas.drawText(text, 0, 6, paint);
  }

  @Override
  public void setAlpha(int alpha) {
      paint.setAlpha(alpha);
  }

  @Override
  public void setColorFilter(ColorFilter cf) {
      paint.setColorFilter(cf);
  }

  @Override
  public int getOpacity() {
      return PixelFormat.TRANSLUCENT;
  }
}

然后将edittext左侧的drawable设置为

Then set the drawable to left of the edittext as

EditText et = (EditText)findViewById(R.id.editText1);
String code = "+374";
et.setCompoundDrawablesWithIntrinsicBounds(new TextDrawable(code), null, null, null);
et.setCompoundDrawablePadding(code.length()*10);

其中edittext在布局文件中定义为

Where the edittext is defined in the layout file as

<EditText
android:id="@+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:ems="10" >
  <requestFocus />
</EditText>

最终输出的样子

这篇关于设置不可更改的editText android的某些部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆