Multicolored edittext hint

2019-06-24 05:24发布

问题:

Is there a way to set multiple colors to the edittext's hint when wrapped by android.support.design.widget.TextInputLayout without compromising the behaviour of floating edittexts?

like, Headline*

Headline and * with different colored hint

回答1:

Use SpannableString class which allows you to use different styles on parts of your string ... If I remember correctly, TextAppearanceSpan class is used for coloring a text..



回答2:

See below code this is work for me.

 EditText editText = (EditText) findViewById(textView);
 Spannable wordtoSpan = new SpannableString("Hello world");

 wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 2, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

 editText.setHint(wordtoSpan);


回答3:

You can acheive this by programtically

SpannableString spString = new SpannableString("HEADERLINE*");
    spString.setSpan(new ForegroundColorSpan(Color.MAGENTA), 11,     spString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    metUserName.setHint(spString);


回答4:

Try this! If you want to use it for setText just add BufferType.SPANNABLE (see below)

    String redPart = "Hello";
    String bluePart = "World";

    SpannableStringBuilder builder = new SpannableStringBuilder();

    SpannableString redColoredString= new SpannableString(redPart);
    redColoredString.setSpan(new ForegroundColorSpan(Color.RED), 0, redPart.length(), 0);
    builder.append(redColoredString);

    SpannableString blueColoredString= new SpannableString(bluePart);
    blueColoredString.setSpan(new ForegroundColorSpan(Color.BLUE), 0, bluePart.length(), 0);
    builder.append(blueColoredString);


    myEditText.setHint(builder)

    //do following for setText
    myEditText.setText(builder,BufferType.SPANNABLE)