如何验证android中的文本样式

时间:2014-04-02 09:31:45

标签: android android-edittext text-editor rich-text-editor

我正在开发一个简单的文本编辑器,在android中有一些基本选项,如粗体,斜体,粗体+斜体,下划线。以下是我在单击相应按钮时将效果应用于所选文本的代码。

public void buttonClick(View target){
    Log.i("Information  ", "In click");
    View parentView = (View) target.getParent();
    final EditText editorField = (EditText) parentView.findViewById(R.id.editor_field);
    int startSelection = editorField.getSelectionStart();
    int endSelection = editorField.getSelectionEnd();
    Spannable textEdit = editorField.getText();

    if(target.getId() == R.id.boldButton){
        textEdit.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), startSelection, endSelection, 0);
    } else if(target.getId() == R.id.italicButton){
        textEdit.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), startSelection, endSelection, 0);
    } else if(target.getId() == R.id.underlineButton){
        textEdit.setSpan(new UnderlineSpan(), startSelection, endSelection, Spannable.SPAN_MARK_MARK);
    } else if(target.getId() == R.id.strikeButton){
        textEdit.setSpan(new StrikethroughSpan(), startSelection, endSelection, Spannable.SPAN_MARK_MARK);
    } else if(target.getId() == R.id.boldItalicButton){
        textEdit.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), startSelection, endSelection, 0);
    } 
}

但是在应用文本效果之前,我必须检查所选文本是否已经具有任何文本效果。即最初所选文本以粗体显示,因此当单击粗体按钮时,必须删除该文本效果。我不明白该怎么做。任何人都可以帮助我。

问候。

1 个答案:

答案 0 :(得分:1)

您可以获取调用getSpans()方法的样式列表:

StyleSpan[] styleSpans = textEdit.getSpans(startSelection, endSelection, StyleSpan.class);

然后使用StyleSpan类的方法:

if (styleSpans[i].getStyle() == android.graphics.Typeface.BOLD){
    ...  
}