我想在按钮点击时更改文字样式。当用户单击该按钮时,它会使所选区域为斜体。当用户再次单击它时,我希望所选区域变为非斜体。这怎么可能。这是我的代码:
if (id == R.id.italic) {
int startSelection = noteContent.getSelectionStart();
int endSelection = noteContent.getSelectionEnd();
Spannable spannable = noteContent.getText();
StyleSpan[] spans = spannable.getSpans(startSelection, endSelection, StyleSpan.class);
if (spans.length == 0 ) {
spannable.setSpan(new StyleSpan(Typeface.ITALIC), startSelection, endSelection , 0);
} else {
StyleSpanRemover spanRemover = new StyleSpanRemover();
spanRemover.RemoveStyle(spannable, startSelection, endSelection, Typeface.ITALIC);
}
}
当我运行此代码时,所选区域在按钮单击时变为斜体。然后,如果我再次单击该按钮,则相同的选定区域将变为非斜体。听起来它很好。但事实并非如此。出于某种原因,如果我采用相同的选定区域并重新设计它,它将不会变成斜体。这是因为spans.length仍然设置为1.当我使斜体文本正常时,它没有回到零。有关如何将spans.length设置回0的想法吗?