我有以下功能 -
private fun initData() {
tasksViewmodel.getGroupsAndTasksCounter().observe(requireActivity(), Observer {model ->
if (model.groupsCount == 0 && model.tasksCount == 0) {
return@Observer
}
val spannableStringBuilder = SpannableStringBuilder()
val color = requireContext().getColor(R.color.black)
val foregroundColorSpan = ForegroundColorSpan(color)
val groupsBold = SpannableString(model.groupsCount.toString()
.plus(" ")
.plus(getString(R.string.groups)))
val tasksBold = SpannableString(model.tasksCount.toString()
.plus(" ")
.plus(getString(R.string.groups_info_ongoing_tasks)))
groupsBold.setSpan(foregroundColorSpan, 0, groupsBold.length, 0)
groupsBold.setSpan(StyleSpan(Typeface.BOLD), 0, groupsBold.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
groupsBold.setSpan(RelativeSizeSpan(1.1f), 0, groupsBold.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
tasksBold.setSpan(foregroundColorSpan, 0, tasksBold.length, 0)
tasksBold.setSpan(StyleSpan(Typeface.BOLD), 0, tasksBold.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
tasksBold.setSpan(RelativeSizeSpan(1.1f), 0, tasksBold.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
spannableStringBuilder.append(getString(R.string.groups_info_participating_in)
.plus(" ")
.plus(groupsBold)
.plus(" ")
.plus(getString(R.string.groups_info_and_you_have))
.plus(" ")
.plus(tasksBold)
.plus(getString(R.string.dot)))
spannableStringBuilder.toString()
sharedInformationViewModel.value.groupsInfoString.value = spannableStringBuilder.toString()
})
}
以及以下共享视图模型 -
class SharedInformationViewModel : ViewModel() {
....
val groupsInfoString = MutableLiveData<String>()
}
我在其他片段中使用字符串值 -
private fun initData() {
sharedInformationViewModel.value.groupsInfoString.observe(requireActivity(), Observer { info ->
binding.groupsGroupsAndTasksCounter.setText(info, TextView.BufferType.SPANNABLE)
})
}
该字符串确实是正确的。
我面临的问题是,由于某种原因,spannablestring 不会改变颜色并且不会使文本变为粗体,即使这段代码与我的应用程序中的另一段代码重复。
我错过了什么?