如何创建带有两种颜色文本的文本视图?

问题描述

我想创建一个 TextView 并有两个文本或两种颜色的文本...

我创造了这个;

enter image description here

并且我希望样品店颜色更改为红色并搜索为蓝色...

我的 xml 代码

    <TextView
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:layout_marginLeft="5dp"
    android:layout_marginTop="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginBottom="5dp"
    android:background="@drawable/search_bg"
    android:drawableRight="@drawable/search"
    android:drawableTint="@color/day_dark_blue"
    android:paddingRight="15dp"
    android:gravity="center"
    android:layout_gravity="center|center_vertical"
    android:text="search in Sample Shop"
    android:textColor="@color/day_dark_blue"
    android:textSize="18sp" />

解决方法

您可以尝试使用 SpannableString

// in the .kt file
val spannable = SpannableString("search in the Sample Shop")
    
spannable.setSpan(
     ForegroundColorSpan(Color.RED),10,20,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

// 10,20: start and end index of Sample Shop

myTextView.text = spannable

一篇有用的文章:Spantastic text styling with Spans

,

您可以使用 SpannableString 来实现相同的效果。

TextView TV = (TextView)findViewById(R.id.textView);

Spannable wordtoSpan = new SpannableString("search in Sample Shop");        

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

wordtoSpan.setSpan(new ForegroundColorSpan(Color.RED),21,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

TV.setText(wordtoSpan);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...