Set unchangeable some part of editText android

前端 未结 5 872
青春惊慌失措
青春惊慌失措 2020-11-30 01:03

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 nu

5条回答
  •  猫巷女王i
    2020-11-30 01:47

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

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

    Where the edittext is defined in the layout file as

    
      
    
    

    Final Output looks like

    enter image description here

提交回复
热议问题