修改字串中某些子字串的顏色
阿新 • • 發佈:2019-02-02
StringBuilder localStringBuilder = new StringBuilder(); localStringBuilder.append("unknow" + "\n"); localStringBuilder.append("0123456789" + "\n"); localStringBuilder.append("MAC地址未燒錄" + "\n"); localStringBuilder.append("未開啟wifi,獲取不了MAC地址" + "\n"); localStringBuilder.append("unknow" + "\n"); localStringBuilder.append("SN未燒錄" + "\n"); localStringBuilder.append("SN未燒錄" + "\n"); SpannableStringBuilder style = new SpannableStringBuilder(); String text = localStringBuilder.toString(); style.append(text); if (text.contains("MAC地址未燒錄")){ int tb = text.indexOf("MAC地址未燒錄"); style.setSpan(new ForegroundColorSpan(Color.RED), tb, tb+8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } for (int index = 0; index>=0 && index<text.length(); ) { index = text.indexOf("SN未燒錄", index); if (index >= 0){ style.setSpan(new ForegroundColorSpan(Color.GREEN), index, index+5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); index++; } } mStringInfo.setText(style); //mStringInfo為TextView,style為按要求修改好的字串