设置TextView部分文字的颜色和背景(高亮显示)

public class Test extends Activity {
private String strs="我的心太乱ewrwer了,给我点空白。";
private TextView textview;
private Button btn1, btn2;
private SpannableStringBuilder style;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

loadView();
}
private void loadView(){
btn1 = (Button) findViewById(R.id.btn1);
btn2 = (Button) findViewById(R.id.btn2);
textview = (TextView) findViewById(R.id.tv);
style=new SpannableStringBuilder(strs);
btn1.setText("蓝色");
btn2.setText("红色");
btn1.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
style.setSpan(new BackgroundColorSpan(Color.BLUE),0,strs.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textview.setText(style);
}
});
btn2.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
style.setSpan(new BackgroundColorSpan(Color.RED),0,strs.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textview.setText(style);
}
});
}
}

你可能感兴趣的:(android)