我有一个由 ListView 组成的警报对话框。在该列表中,第一个选项是“创建监视列表”。该列表中的其余选项是应用程序中所有其他可用的监视列表。我想要的是:
- 加强“创建监视列表”
- 更改“创建监视列表”的颜色
我已经尝试了 4 种方法来实现这一点,但都没有奏效。我将所有方法都以项目符号形式列出。
在 strings.xml 中存储和格式化“Create WatchList”并从适配器调用它,但它仍然不起作用
<string name="create_watchlist"><b>Create Watchlist</b></string>
在 Java 中
String createWatchList = context.getResources().getString(R.string.create_watchlist);
然后我将它添加到列表中
alertList.add(0,createWatchList);
使用上述方法,文本显示时没有格式。
然后我使用 fromHtml 函数,但我仍然得到相同的结果
CharSequence styledString = Html.fromHtml(createWatchList );
然后我将它添加到列表中
alertList.add(0,styledString.toString());
然后我在 TextView 中尝试了这个,但似乎 ListViews 不能接受 TextView 。
我最近试过的是这样的:
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
int start = 0;
spannableStringBuilder.append(createWatchlist);
spannableStringBuilder.setSpan(new ForegroundColorSpan(0xFFCC5500),start,start+createWatchlist.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableStringBuilder.setSpan(new StyleSpan(Typeface.BOLD),start,start+createWatchlist.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
alertList.add(0,spannableStringBuilder.toString());
- 我试过这个新方法:
TextView textView = new TextView(context);
textView.setText(createWatchlist);
textView.setTypeface(textView.getTypeface(),Typeface.BOLD);
textView.setTextColor(context.getResources().getColor(R.color.lightRed));
alertList.add(0,textView);
尝试上述新方法后,我收到一条消息“第二个参数类型错误。找到:'android.widget.TextView',需要:'java.lang.String'”
以上方法都不适合我。任何对此有任何解决方案的人请帮忙!!!
最佳答案
您可以在适配器内设置 TextView 的样式和颜色。只需检查它是否是第一项,然后用 TextView 做任何你想做的事。
将其设为粗体:
textView.setTypeface(textView.getTypeface(), Typeface.BOLD)
设置颜色:
textView.setTextColor(getResources().getColor(R.color.yourColor));
关于java - 如何更改 ListView 中特定字符串的字体颜色和样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58110954/