1.Processing Text 處理字串
Input: original text 原始字串
Output: edited text 編輯後字串
// neMAp = <span content, span id> private HashMap neMap = new HashMap(); // neLength = span content length private ArrayList neLength = new ArrayList(); // get <span> id and content // replace <span>content</span> to <util>content // 取得<span>的id和所包的文字內容 // 將<span>文字內容</span>換成<util>content private String parseContent(String text) { String[] contArray = text.split("<span id=\""); ArrayList keyArray = new ArrayList(); for (String ca : contArray) { String span = ca.split("</span>")[0]; keyArray.add(span); } for(int i = 1 ; i < keyArray.size() ; i++){ String[] temp = keyArray.get(i).split("\">"); neMap.put(temp[1], temp[0]); neLength.add(temp[1].length()); text = text.replace("<span id=\""+temp[0]+"\">"+temp[1]+"</span>", "<util>"+temp[1]); } return text; }
2.Set SpannableStringBuilder 設定字串Span
private SpannableStringBuilder getItemSetArray(String text) { String[] itemSetArray = text.split("<util>"); text = text.replace("<util>", ""); SpannableStringBuilder spannable = new SpannableStringBuilder(text); for (int i = 1 ; i < itemSetArray.length ; i++) { spannable.setSpan(new ItemSetSpan(itemSetArray[i], this.getResources().getColor(R.color.blue), false, neLength.get(i-1)), text.indexOf(itemSetArray[i]), // span content start position text.indexOf(itemSetArray[i])+neLength.get(i-1), // span content end position, use neLength list Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } return spannable; } public class ItemSetSpan extends ClickableSpan { private String text; private int color; private boolean isItemSetName; public ItemSetSpan(String text, boolean isItemSetName) { this.text = text; this.isItemSetName = isItemSetName; } public ItemSetSpan(String text, int color, boolean isItemSetName, Integer text_length) { this.text = text.substring(0, text_length); this.color = color; this.isItemSetName = isItemSetName; } @Override public void onClick(View widget) { if (isItemSetName) { } else { showSimpleItem(text); // click function } } @Override public void updateDrawState(TextPaint ds) { if (!isItemSetName) { ds.setColor(color); ds.setUnderlineText(true); } } } private void showSimpleItem(String text){ // Do your action 自行設定點選後動作 Result_TextView.setText(text+"_id: "+neMap.get(text)); } // Original TextView must setMovementMethod // 欲設定點選的TextView必須設定setMovementMethod Original_TextView.setMovementMethod(LinkMovementMethod.getInstance());
3.Run Test 測試
// Test String 測試用字串 private String test = "<span id=\"1\">Jack</span>_no.1\n<span id=\"2\">Allen</span>_no.2\n<span id=\"3\">Mark</span>_no.3";
Before click
After click
文章標籤
全站熱搜
留言列表