您的位置:首页 > 移动开发 > Android开发

改变textview的部分字体和颜色

2016-04-22 09:49 417 查看
textview是android系统体提供显示文本的一类组件,在实际的使用中,一段文字可能需要不同的颜色和文字。常用的实现方法有两类,分别是textview的textview.setText(Html.fromHtml("显示的内容和样式"))方法和SpannableString。SpannableString方法比较灵活。
实现如下:


1.布局文件定义4个textview

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>

<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text1" />

<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text2" />

<TextView
android:id="@+id/tv3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text3" />

<TextView
android:id="@+id/tv4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text4" />

</LinearLayout>


2.找到四个textview,并实现效果

private TextView tv1 = null;
private TextView tv2 = null;
private TextView tv3 = null;
private TextView tv4 = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.tv1);
tv2 = (TextView) findViewById(R.id.tv2);
tv3 = (TextView) findViewById(R.id.tv3);
tv4 = (TextView) findViewById(R.id.tv4);
tv1.setText(Html.fromHtml("我是<font color='#ff0000'><big>第一个</big>textview </font>"));
tv2.setText(Html.fromHtml("<h1>我是第二个textview</h1>"));
tv3.setText("我是第三个textview");
Spannable sp=new SpannableString(tv3.getText());
sp.setSpan(new AbsoluteSizeSpan(50), 2, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
sp.setSpan(new ForegroundColorSpan(Color.RED), 2, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv3.setText(sp);
tv4.setText(Html.fromHtml("<font color='#ffff00'>
<small>我是第四个textview</small></font>"));`
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android textview