android TextView 設定部分文字背景色和文字顏色,androidtextview
通過SpannableStringBuilder來實現,它就像html裡邊的<span>元素改變指定文字的文字顏色或背景色
public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);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);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}
- AbsoluteSizeSpan(int size) ---- 設定字型大小,參數是絕對數值,相當於Word中的字型大小
- RelativeSizeSpan(float proportion) ---- 設定字型大小,參數是相對於預設字型大小的倍數,比如預設字型大小是x, 那麼設定後的字型大小就是x*proportion,這個用起來比較靈活,proportion>1就是放大(zoom in), proportion<1就是縮小(zoom out)
- ScaleXSpan(float proportion) ---- 縮放字型,與上面的類似,預設為1,設定後就是原來的乘以proportion,大於1時放大(zoon in),小於時縮小(zoom out)
- BackgroundColorSpan(int color) ----背景著色,參數是顏色數值,可以直接使用android.graphics.Color裡面定義的常量,或是用Color.rgb(int, int, int)
- ForegroundColorSpan(int color) ----前景著色,也就是字的著色,參數與背景著色一致
- TypefaceSpan(String family) ----字型,參數是字型的名字比如“sans", "sans-serif"等
- StyleSpan(Typeface style) -----字型風格,比如粗體,斜體,參數是android.graphics.Typeface裡面定義的常量,如Typeface.BOLD,Typeface.ITALIC等等。
- StrikethroughSpan----如果設定了此風格,會有一條線從中間穿過所有的字,就像被劃掉一樣
安卓開發:怎靜態與動態設定textView的文本與背景色彩,怎填?初學不知填啥要詳細
靜態就是在可視化的Graphical Layout內的屬性內填
textView1.TextColor(文本色)
textView1.Background(背景色)
中填 @android就會自動彈出所有定義的色彩值
如 @android:color/holo_blue_bright
動態就是程式中設定色彩
import android.graphics.Color;
textView1.setTextColor(Color.RED);
textView1.setBackgroundColor(Color.RED);
怎設定一個TextView在被點擊時改變背景色?
在onclick事件中添加
getCodeView.setTextColor(Color.RED);//點擊修改顏色
//還原成原來的黑色
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
getCodeView.setTextColor(Color.BLACK);
}
}, 200);
/