android textview设置背景和前景,view选中状态

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android" >  
  3.     <item android:state_pressed="true">  
  4.         <shape android:shape="rectangle">  
  5.             <solid android:color="#11000000"/>  
  6.         </shape>  
  7.     </item>  
  8.      <item android:state_pressed="false">  
  9.         <shape android:shape="rectangle">  
  10.             <!-- 透明色 -->  
  11.             <solid android:color="#00000000"/>  
  12.         </shape>  
  13.     </item>  
  14.   
  15. </selector>  
      String str="这是设置TextView部分文字背景颜色和前景颜色的demo!";
        int bstart=str.indexOf("背景");
        int bend=bstart+"背景".length();
        int fstart=str.indexOf("前景");
        int fend=fstart+"前景".length();
        SpannableStringBuilder style=new SpannableStringBuilder(str); 
        style.setSpan(new BackgroundColorSpan(Color.RED),bstart,bend,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);   
        style.setSpan(new ForegroundColorSpan(Color.RED),fstart,fend,Spannable.SPAN_EXCLUSIVE_INCLUSIVE); 
        TextView tvColor=(TextView) findViewById(R.id.tv_color);
        tvColor.setText(style);

猜你喜欢

转载自blog.csdn.net/meixi_android/article/details/79231092