java - 如何从相邻文本中获取文本颜色
问题描述
我正在开发一个 android 应用程序,在该应用程序中,我可以使用可扩展的字符串将不同的颜色应用于 edittext 的文本,并通过 ActivityResult 获取颜色,它工作得很好,但是当我开始输入更多文本时,它会得到默认颜色,即黑色。请注意,我只使用了一个编辑文本。现在我想添加一个功能,可以在选择颜色后输入颜色。另外,我想要另一个功能,当单击另一种颜色的文本附近时,它会自动获取该文本颜色,并且当一个人开始键入时,它会输入该颜色。意思是我想从相邻的文本颜色中获取颜色。我尝试了以下方法,但它为我的整个文本着色。我不希望我的整个文本获得相同的颜色。
text.setTextColor(Color.parseColor(color));
这是我的可扩展字符串颜色编码,它工作正常。
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RequestCode && resultCode == RESULT_OK && data != null) {
color = data.getStringExtra("color");
texto.setTextColor(Color.parseColor(color));
}
Spannable str = texto.getText();
int selStart = texto.getSelectionStart();
int selEnd = texto.getSelectionEnd();
ForegroundColorSpan[] styleSpans = texto.getText().getSpans(selStart, selEnd, ForegroundColorSpan.class);
if (styleSpans.length > 0) {
int lastSpanEnd = 0;
for (ForegroundColorSpan styleSpan : styleSpans) {
int oldStyle = styleSpan.getForegroundColor();
int spanStart = str.getSpanStart(styleSpan);
int spanEnd = str.getSpanEnd(styleSpan);
str.removeSpan(styleSpan);
if (spanStart < selStart) {
str.setSpan(new ForegroundColorSpan(oldStyle), spanStart, selStart, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (spanEnd > selEnd) {
str.setSpan(new ForegroundColorSpan(oldStyle), selEnd, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
if (selEnd != lastSpanEnd) {
str.setSpan(new ForegroundColorSpan(Color.parseColor(color)), selStart, selEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
else {
str.setSpan(new ForegroundColorSpan(Color.parseColor(color)), selStart, selEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
解决方案
推荐阅读
- angular - 如何避免 RouterLink 删除尾随反斜杠
- php - 美化 PHP 和 HTML 语句的混合
- sdk - 在 DM 脚本线程中阻塞 sdk 包装函数
- rust - 如何将 rust ndarray 写入 HDF5 数据集?
- pyqt5 - 如何检测在 PyQt5 中按下了动态添加的按钮之一?
- docker - 无法创建 GCP Cloud Shell 自定义映像
- postman - 使用日期范围运行 newman?
- php - 在 ECS wordpress 上挂载 EFS 的位置?
- php - Laravel 类 App\Repositories\FirebaseUserRepository 未找到
- kotlin - 当我使用多个流时,Kafka Streams StreamsException