【问题标题】:How to make a part of text bold from arraylist in android如何从android中的arraylist使部分文本变为粗体
【发布时间】:2015-01-11 11:28:16
【问题描述】:

在我的 android 应用程序中,我从 mysql 数据库中检索数据,将它们存储在 arraylist 中并在列表视图中显示它们。现在我想将一个特殊的字符串加粗,即如果在我的数组列表中有类似“Me: hello..”的数据,那么在列表视图中它应该显示为“Me: hello..”。这里 "Me:" 将是列表中的第一个字符串,但不知道在哪一行。我不知道如何做到这一点。请有人帮助我..!!

【问题讨论】:

  • 为什么不让你的arraylist 保存包含你作为字符串保存的文本的对象,然后不管它们是否作为布尔值加粗?
  • 在适配器中创建视图时,如果条件通过,您可以检查数组列表项的值,然后相应地使文本变为粗体。
  • 或者更好,if(text.equals(me)){//make bold}
  • @DreadHeadedDeveloper 我不想将完整的文本设置为粗体。我想要一个固定的部分,比如我:你好,只有我:应该是粗体。

标签: java android mysql listview arraylist


【解决方案1】:

尝试使用下面提到的代码:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView mTV = (TextView) findViewById(R.id.tv);
    String mString = "Me: hello..";
    mTV.setText(boldText(mString,0,2));
}
private Spannable boldText(String mText, int mStart, int mEnd) {

    Spannable WordtoSpan = new SpannableString(mText);
    WordtoSpan.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), mStart, mEnd,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return WordtoSpan;
}
}

【讨论】:

    【解决方案2】:

    尝试使用自定义函数使文本部分变为粗体:

    示例:

    getTextWithBoldSection("我:你好..","我:");

    public SpannableStringBuilder getTextWithBoldSection(String fulltext, String boldText){
    
            SpannableStringBuilder builder=new SpannableStringBuilder();
    
            if(boldText.length() > 0 && !boldText.trim().equals("")){
                int startingIndex = fulltext.indexOf(boldText);
                int endingIndex = startingIndex + boldText.length();
             
                if(startingIndex < 0 || endingIndex <0){
                    return builder.append(fulltext);
                }
                else if(startingIndex >= 0 && endingIndex >=0){
                    builder.append(fulltext);
                    builder.setSpan(new StyleSpan(Typeface.BOLD), startingIndex, endingIndex, 0);
                }
            }else{
                return builder.append(fulltext);
            }
    
            return builder;
        }
    

    【讨论】:

      【解决方案3】:

      试试下面的代码:

      if(array.get(i).contain("Me")){
          String value = array.get(i).split(":")[0];
          String value1 = array.get(i).split(":")[1];
          String main_value = "<b>"+value +":</b> "+ value1;
      
          txt.setText( Html.fromHtml(main_value));
      }
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多