当前位置:操作系统 > 安卓/Android >>

Android利用SpannableStringBuilder设置TextView中部分文字的颜色

package cc.testspannablestringbuilder;

import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.widget.TextView;
import android.app.Activity;
import android.graphics.Color;
/**
 * Demo描述:
 * 利用SpannableStringBuilder设置TextView中部分文字的颜色
 * 
 * 注意事项:
 * mSpannableStringBuilder.setSpan
 * (new ForegroundColorSpan(Color.RED), 1, 3, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);     
 * 第一个参数:颜色
 * 第二个参数:开始位置
 * 第三个参数:终止位置
 * 第三个参数:SPAN_EXCLUSIVE_INCLUSIVE.用来对第二个和第三个参数进一步限制和说明
 * 此处表示不包含1,但是包含3.从字面意思也很好理解
 */
public class MainActivity extends Activity {
    private TextView mTextView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		init();
	}
    private void init(){
    	mTextView=(TextView) findViewById(R.id.textView);
    	
        String str=" Hello everyone!";
        SpannableStringBuilder mSpannableStringBuilder=new SpannableStringBuilder(str); 
        
        mSpannableStringBuilder.setSpan
        (new ForegroundColorSpan(Color.RED), 1, 3, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);     
        mSpannableStringBuilder.setSpan
        (new ForegroundColorSpan(Color.GREEN), 5, 9, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        mTextView.setText(mSpannableStringBuilder);
        
    }

}
<RelativeLayout 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"
   >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:layout_centerInParent="true" />

</RelativeLayout>

 

补充:移动开发 , Android ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,