2017-03-09 214 views
1

我希望我的editText能夠以粗體,斜體和帶正常文本的下劃線書寫文本。在edittext中編寫文本時使文本變粗體,斜體或下劃線

如:

天氣不錯今天

我知道我可以使用html標籤,但我想在edittext中編寫時執行這些操作。

我曾嘗試:

//here textEdits is my model to store the string. As I have multiple editTexts in the activity. 
@Override 
     public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { 

       if(isBold){ 
        String textsequence = textEdits.get(position).getTextString(); 
        if(i > 0){ 
          String sequence = charSequence.subSequence(0, i).toString() +"<b>"+ charSequence.subSequence(i,i+i3).toString() + "</b>"; 
          textEdits.get(position).setTextString(sequence.toString()); 
          editTextcurrrent.setText(Html.fromHtml(sequence.toString())); 
          editTextcurrrent.setSelection(i+i3); 
         } 
        } 
       } 
       else { 
        textEdits.get(position).setTextString(charSequence.toString()); 
       } 
      } 
     } 

問題: 的CharSequence中返回不包含HTML標籤一個字符串,所以,一旦你已經設置的值,下一次你會得到不包含HTML標籤一個字符串,因此你不能跟蹤你以前的html編輯。

除此之外,我嘗試過字體,但即使這樣也行不通。 也道歉,如果我嘗試的工作是不是很容易理解,它是一個大代碼的一部分,所以有很多鏈接,我試圖刪除儘可能多的依賴關係,因爲我可以。

回答

-1

使用OnFocusChange監聽&變化的EditText屬性,只要你喜歡,當用戶

你也可以在XML中設置粗體和斜體的EditText獲取焦點。

<EditText 
       android:id="@+id/edittext" 
       android:layout_margin="@dimen/activity_horizontal_margin" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:textStyle="bold|italic" 
       android:text="enter your name"/> 
+0

但是這會使整個文本變爲粗體。不只是它的一部分。 –

+0

這將使整個文本變爲粗體。在回答 – Rajan1404930

+0

@ Adrian-AlexandruComan之前,請正確地閱讀這個問題,你可以使用SpannableString來自定義段落中的某些部分。 – lisha

1

你將要使用SpannableString:

String yourString = "The weather is nice today." 
SpannableString contentSpan = new SpannableString(yourString); 
contentSpan.setSpan(new TextAppearanceSpan(activity, R.style.bold_style), weatherFirstPos, weatherLastPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
contentSpan.setSpan(new TextAppearanceSpan(activity, R.style.italic_style), niceFirstPos, niceLastPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
editTextcurrrent.setText(contentSpan, TextView.BufferType.SPANNABLE); 

對於R.style.bold_style和italic_style你可以有這樣的:

<style name="bold_style"> 
    <item name="android:textStyle">bold</item> 
    <item name="android:textColor">@color/black</item> 
</style> 

weatherFirstPos,weatherLastPos,niceFirstPos和niceLastPos是您想要應用風格的位置:

int weatherFirstPos = yourString.indexOf("weather"); 
int weatherLastPos = weatherFirstPos + "weather".length(); 
相關問題