android_5 修改一个textview中的字符串的颜色
16lz
2021-01-26
例:Hello World, 欢迎观看《android教程》哈哈!
要求把《android教程》变红,其他为绿
给textView定义一个id,定义id的方法:android:id="@+id/tv"
android:autoLink="all" 表示web/mail/map之类的都加链接
修改main.xml:
<TextView android:id="@+id/tv" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="20sp" android:textColor="#00ff00" android:text="@string/say" />
String.xml:
<?xml version="1.0" encoding="utf-8"?><resources> <string name="hello">Hello World, TextVitwDemoActivity!</string> <string name="say">Hello World, 欢迎观看《android教程》哈哈!</string> <string name="app_name">TextViewDemo</string></resources>
TextVitwDemoActivity.java:
package com.mhm.textView;import android.app.Activity;import android.os.Bundle;import android.text.Html;import android.widget.TextView;public class TextVitwDemoActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView tv = (TextView)findViewById(R.id.tv); String text = tv.getText().toString(); int tb = text.indexOf("《"); int te = text.indexOf("》") + 1; String text_b = text.substring(0, tb); String text_m = text.substring(tb, te); String text_e = text.substring(te, text.length()); tv.setText(Html.fromHtml(text_b + "<font color=red>" + text_m + "</font>" + text_e)); }}
也可以这样写:
package com.mhm.textView;import android.R.color;import android.app.Activity;import android.graphics.Color;import android.os.Bundle;import android.text.Html;import android.text.Spannable;import android.text.SpannableStringBuilder;import android.text.style.ForegroundColorSpan;import android.widget.TextView;public class TextVitwDemoActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView tv = (TextView)findViewById(R.id.tv); String text = tv.getText().toString(); int tb = text.indexOf("《"); int te = text.indexOf("》") + 1; SpannableStringBuilder style = new SpannableStringBuilder(text); style.setSpan(new ForegroundColorSpan(Color.GREEN), 0, tb, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); style.setSpan(new ForegroundColorSpan(Color.RED), tb, te, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); style.setSpan(new ForegroundColorSpan(Color.GREEN), te, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); tv.setText(style); }}
这里有个奇怪的地方,int te = text.indexOf("》") + 1
+1必须写在这里,写在下面就不行。。。啥原因?
更多相关文章
- ActionBarSherlock使用教程
- Android(安卓)View 下拉刷新之头部效果自定义 [水]
- android studio 自定义路径安装报错"You are attempting to inst
- Android中自定义底部弹出框ButtomDialog
- Android自定义View以及layout属性全攻略
- Android中的DatePickerDiaolog的使用
- Android全局变量的定义与使用
- Android初级教程_用ExpandableListView实现类似QQ好友列表
- 【Android(安卓)Developers Training】 99. 获取联系人详细信息