問題描述
我正在開發 Android 中的富文本編輯器.基本上,它具有與 EditText 相關聯的粗體、斜體和鏈接按鈕,以更改內容的樣式.如果您先選擇要設置樣式的文本,然后使用以下方法選擇按鈕,我會很好地工作:http://developer.android.com/guide/appendix/faq/commontasks.html#selectingtext.
I'm working on a rich text editor in Android. Basically it has bold, italics and link buttons that are tied to an EditText to change the style of the content. I have it working great if you select the text you want to style first, and then select the button using this method: http://developer.android.com/guide/appendix/faq/commontasks.html#selectingtext.
我想做的是讓它像富文本編輯器一樣工作,您可以在其中使用按鈕作為切換來設置文本樣式,只要您愿意,然后再次單擊切換以停止使用風格.因此,如果我想以粗體輸入注意這一點!",我會單擊B"按鈕,然后開始輸入文本,我輸入的所有內容都會變為粗體,直到我單擊B"' 按鈕.
What I'm trying to do is have it work like a rich text editor, where you can use the buttons as a toggle to style the text for as long as you'd like, then click the toggle again to stop using the style. So if I wanted to type 'Pay attention to this!' in bold, I would click the 'B' button, then start typing the text and everything I type would be bold until I click the 'B' button again.
關于如何實現這一點的任何想法?我希望我已經足夠清楚了:)
Any ideas on how to pull this off? I hope I've been clear enough :)
推薦答案
您可以在他們鍵入的每個字符之后使用 TextWatcher
和 addTextChangedListener()
方法.
You could just update the style after every character that they type using a TextWatcher
and the addTextChangedListener()
method.
好的,這只是簡單的示例代碼.
Ok, this is just the bare bones example code.
int mStart = -1;
// Bold onClickListener
public void onClick(View view)
{
if(mStart == -1) mStart = mEditText.getText().length();
else mStart = -1;
}
// TextWatcher
onTextChanged(CharSequence s, int start, int before, int count)
{
if(mStart > 0)
{
int end = mEditText.getText().length();
mEditText.getText().setSpan(new StyleSpan(android.graphics.Typeface.BOLD), mStart, end - mStart, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
這篇關于樣式 EditText 內容'即時'?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!