【问题标题】:How to fill `EditText` items with different colors?如何用不同的颜色填充“EditText”项目?
【发布时间】:2017-12-05 03:51:42
【问题描述】:

我可以在这样的 EditText 项目中填充不同的颜色吗?

当然,我可以使用两个EditText,但我很好奇它可以使用EditText

【问题讨论】:

  • 好问题,但需要更清楚。
  • @GokulSreenivasan 谢谢你的评论 :)

标签: android xml layout android-edittext


【解决方案1】:

是的,你可以,你必须使用 Spannable 类。

final String yourText = "Your text to be filled";
final int length_you_want = 5;
Spannable modifiedText = new SpannableString(yourText);
modifiedText.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.green)), 0, length_you_want, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(modifiedText);

【讨论】:

  • 谢谢你的回答:)
【解决方案2】:

如果你有两个不同的文本要着色,然后组合成一个,你可以做不同的事情;

 public String getColoredString(String pname) {
    Random rnd = new Random();
    int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
    Spannable wordToSpan = new SpannableString(pname);
    wordToSpan.setSpan(new ForegroundColorSpan(color), 0, pname.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return wordToSpan.toString();
}

将字符串传递给方法并在需要的地方使用它。

textview.settext(getColoredString("your text1")+getColoredString("your text2));

【讨论】:

    猜你喜欢
    • 2020-12-03
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    • 1970-01-01
    相关资源
    最近更新 更多