Android 将样式应用于textview中的特定字符

Android 将样式应用于textview中的特定字符,android,Android,目前我正在使用26Textview,以便根据运行时的情况将样式应用于特定字符。 但如果我能够在textview中对特定字符应用样式,我就可以只使用一个textview来实现我的目标 e、 g。 如果我想在下面的代码中将字符“M”变成红色。有可能做到这一点吗 <TextView android:id="@+id/TextView01" android:layout_height="wrap_content" android:textSize="20dip

目前我正在使用26
Textview
,以便根据运行时的情况将样式应用于特定字符。 但如果我能够在textview中对特定字符应用样式,我就可以只使用一个textview来实现我的目标

e、 g。 如果我想在下面的代码中将字符“M”变成红色。有可能做到这一点吗

    <TextView 
    android:id="@+id/TextView01" 
    android:layout_height="wrap_content" 
    android:textSize="20dip" 
    android:textStyle="bold"
    android:layout_width="15dip" 
    android:text="ABCDEFGHIJKLMNOPQRSTUVWXYZ" 
    android:background="#FFFFFF" 
   android:textColor="#000000"/>`
`

或者任何人都有比使用26
TextView更好的选择,这也很受欢迎。

您只能使用1个TextView并通过Html更改颜色。fromHtml()

试试这段代码。这对你有帮助

RelativeLayout rl=(RelativeLayout) findViewById(R.id.rl);
RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams((int)LayoutParams.WRAP_CONTENT,(int)LayoutParams.WRAP_CONTENT);
params.leftMargin=45;
params.topMargin=70;
TextView textView=new TextView(this);
String text = "I Love <font color='red'>ANDROID !!!</font>";
textView.setText(Html.fromHtml(text));
textView.setLayoutParams(params);
textView.setTextSize(25);
rl.addView(textView);
RelativeLayout rl=(RelativeLayout)findViewById(R.id.rl);
RelativeLayout.LayoutParams params=新的RelativeLayout.LayoutParams((int)LayoutParams.WRAP\u内容,(int)LayoutParams.WRAP\u内容);
参数leftMargin=45;
参数topMargin=70;
TextView TextView=新的TextView(此);
String text=“我爱安卓!!!”;
textView.setText(Html.fromHtml(text));
textView.setLayoutParams(参数);
textView.setTextSize(25);
rl.addView(textView);
使用span启用

private SpannableString spanIt(String text, String queryText) {
    // search for query on text
    int startIndex = text.indexOf(queryText);
    int endIndex = startIndex + queryText.length();
    // spannable to show the search query
    SpannableString spanText = new SpannableString(text);
    if (startIndex > -1) {  
        spanText.setSpan(new ForegroundColorSpan(Color.RED), startIndex,
                endIndex, 0);
    }
    return spanText;
}
然后在textview上

tv.settext(spanIt("ABCDEFGHIJLMNOPQRSTUVXZ","M"));

这里有一个例子:那很好;只是稍微抬起头。