gpt4 book ai didi

android - Edittext 的粗体/正常状态

转载 作者:行者123 更新时间:2023-11-29 20:16:28 27 4
gpt4 key购买 nike

对于我的 Edittext,我正在为用户创建能够将选定文本设置为粗体的选项,但用户也应该能够再次“取消加粗”相同的选定文本。

此功能还包括斜体、下划线、描边,但稍后会添加。

使文本加粗的代码有效,但我不知道如何取消所选文本的加粗或如何检查文本是否已经加粗。

  CharacterStyle cs;
int start = editText.getSelectionStart();
int end = editText.getSelectionEnd();
SpannableStringBuilder ssb = new SpannableStringBuilder(editText.getText());

switch(item.getItemId()) {

case R.id.bold:


cs = new StyleSpan(Typeface.BOLD);
ssb.setSpan(cs, start, end, 1);
editText.setText(ssb);
return true;

最佳答案

使用在网络上找到的算法解决:https://code.google.com/archive/p/droid-writer/

int selectionStart = editText.getSelectionStart();
int selectionEnd = editText.getSelectionEnd();

if (selectionStart > selectionEnd) {
int temp = selectionEnd;
selectionEnd = selectionStart;
selectionStart = temp;
}


if (selectionEnd > selectionStart) {
Spannable str = editText.getText();
boolean exists = false;
StyleSpan[] styleSpans;

switch (item.getItemId()) {
case R.id.bold:
styleSpans = str.getSpans(selectionStart, selectionEnd, StyleSpan.class);

// If the selected text-part already has BOLD style on it, then
// we need to disable it
for (int i = 0; i < styleSpans.length; i++) {
if (styleSpans[i].getStyle() == android.graphics.Typeface.BOLD) {
str.removeSpan(styleSpans[i]);
exists = true;
}
}

// Else we set BOLD style on it
if (!exists) {
str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), selectionStart, selectionEnd,
Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
}

editText.setSelection(selectionStart, selectionEnd);
break;

关于android - Edittext 的粗体/正常状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33788823/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com