2015-11-18 23 views
1

對於我的編輯文本,我創建了用戶可以將選定文本設置爲粗體的選項,但用戶還應該能夠「重新打開」相同的選定文本。編輯文本的粗體/正常狀態

此功能還包括斜體,下劃線,中風,但稍後會添加。

使文本加粗的代碼有效,但我不知道如何取消選定的文本或如何檢查文本是否已加粗。

CharacterStyle cs; 
    int start = editText.getSelectionStart(); 
    int end = editText.getSelectionEnd(); 
    SpannableStringBuilder ssb = new SpannableStringBuilder(editText.getText()); 

    switch(item.getItemId()) { 

     case R.id.bold: 


      cs = new StyleSpan(Typeface.BOLD); 
      ssb.setSpan(cs, start, end, 1); 
      editText.setText(ssb); 
      return true; 

回答

0

這種算法在網絡上找到解決:https://code.google.com/archive/p/droid-writer/

int selectionStart = editText.getSelectionStart(); 
int selectionEnd = editText.getSelectionEnd(); 

if (selectionStart > selectionEnd) { 
     int temp = selectionEnd; 
     selectionEnd = selectionStart; 
     selectionStart = temp; 
    } 


    if (selectionEnd > selectionStart) { 
     Spannable str = editText.getText(); 
     boolean exists = false; 
     StyleSpan[] styleSpans; 

     switch (item.getItemId()) { 
      case R.id.bold: 
       styleSpans = str.getSpans(selectionStart, selectionEnd, StyleSpan.class); 

       // If the selected text-part already has BOLD style on it, then 
       // we need to disable it 
       for (int i = 0; i < styleSpans.length; i++) { 
        if (styleSpans[i].getStyle() == android.graphics.Typeface.BOLD) { 
         str.removeSpan(styleSpans[i]); 
         exists = true; 
        } 
       } 

       // Else we set BOLD style on it 
       if (!exists) { 
        str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), selectionStart, selectionEnd, 
          Spannable.SPAN_EXCLUSIVE_INCLUSIVE); 
       } 

       editText.setSelection(selectionStart, selectionEnd); 
       break; 
0

相應地使用,下面的代碼比你更容易實現。

textView.setTypeface(null, Typeface.NORMAL); 
textView.setTypeface(null, Typeface.BOLD_ITALIC); 
textView.setTypeface(null, Typeface.BOLD); 
textView.setTypeface(null, Typeface.ITALIC); 

爲了將指定的文本設置爲粗體,我發現使用Html構建你的字符串要容易得多。例如,如果你想要一些文字看起來像這樣

尼爾

可以使用這樣做:

String sourceString = "<b>" + id + "</b> " + name; 
mytextview.setText(Html.fromHtml(sourceString)); 
+0

我該如何使用它們一些選定的文字而不是全文? – Muddz

+0

我已更新我的回答 –

+0

這不是幫助我或回答我的問題。我希望能夠使用相同的按鈕將選定的文本設置爲粗體,並且如果選定的文本已經是粗體,那麼如果所選文本也包含斜體,則它應該是正常的,而不會丟失斜體樣式。 – Muddz