【问题标题】:How to verify the text style in android如何在android中验证文本样式
【发布时间】:2014-04-02 09:31:44
【问题描述】:

我正在 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);
    } 
}

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

问候。

【问题讨论】:

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


    【解决方案1】:

    调用getSpans()方法可以获得样式列表:

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

    然后使用StyleSpan类的方法:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-10
      • 2012-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多