我正在制作一个应用程序,用户可以在单击按钮时斜体显示可伸缩文本。
// Captures Contextual Menu Clicks//
public void onContextualMenuItemClicked(MenuItem item) {
int id = item.getItemId();
if (id == R.id.bold) {
// do some stuff
}
if (id == R.id.italic) {
int startSelection = noteContent.getSelectionStart();
int endSelection = noteContent.getSelectionEnd();
Spannable spannable = noteContent.getText();
spannable.setSpan(new StyleSpan(Typeface.ITALIC) , startSelection , endSelection , 0);
StyleSpanRemover spanRemover = new StyleSpanRemover();
spanRemover.RemoveStyle(spannable,startSelection,endSelection,Typeface.ITALIC);
}
这段代码让它变成斜体
int startSelection = noteContent.getSelectionStart();
int endSelection = noteContent.getSelectionEnd();
Spannable spannable = noteContent.getText();
spannable.setSpan(new StyleSpan(Typeface.ITALIC) , startSelection , endSelection , 0);
让它变成非斜体
StyleSpanRemover spanRemover = new StyleSpanRemover();
spanRemover.RemoveStyle(spannable,startSelection,endSelection,Typeface.ITALIC
我希望用户单击相同的按钮来斜体和非斜体。我可以使用什么if语句来获取可伸缩选定单词的字体?这样它就知道是否要斜体
更新:这是我现在的
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 {
spannable.setSpan(new StyleSpan(Typeface.NORMAL), startSelection, endSelection , 0);
}
即使代码运行代码
spannable.setSpan(new StyleSpan(Typeface.NORMAL), startSelection, endSelection , 0);
并将其设置为正常。但是它不会设置跨度。长度为0,所以我不能再斜体了如何设置跨度。
您可以使用getSpans(startSelection, endSelection, StyleSpan.class)
查看在选择范围中存在哪些span。基于此,您可以决定是否(以及如何)斜体文本。注意,用户可能会突出显示包含正常文本和斜体文本的部分。
编辑
StyleSpan[] spans = spannable.getSpans(startSelection, endSelection, StyleSpan.class);
if (spans.length == 0) {
// no spans, italicize text here
} else {
// TODO
}