【问题标题】:How to show list of string in TextView on Android如何在 Android 上的 TextView 中显示字符串列表
【发布时间】:2017-12-05 10:23:15
【问题描述】:

我想在TextView 中显示字符串列表,我从服务器获取此列表。
来自 json 的列表:

"stars": [
                    {
                        "name": "Elyes Gabel"
                    },
                    {
                        "name": "Katharine McPhee"
                    },
                    {
                        "name": "Robert Patrick"
                    }
                ]

我想显示这个名字,比如这个样本:

明星 = Elyes Gabel、Katharine McPhee、Robert Patrick

我应该从适配器中的这个TextView setText

使用下面的代码我可以显示名称:

model.get(position).getStars().get(0).getName();

但请告诉我 Elyes Gabel !!!

我想给我看这样的:

明星 = Elyes Gabel、Katharine McPhee、Robert Patrick

我该怎么办?请帮帮我

【问题讨论】:

  • 使用列表视图并将它们显示为列表。或者,如果您有一个 textview 循环遍历值列表并将其附加到 textview
  • @Raghunandan,你能把完整的代码发给我吗?请

标签: android arrays list textview


【解决方案1】:

您需要遍历所有“星”元素并自己构建字符串。你应该有这样的东西:

String concatenatedStarNames = "";
List<Star> stars = model.get(position).getStars(); // I assume the return value is a list of type "Star"!
for (int i = 0; i < stars.size(); i++) {
  concatenatedStarNames += stars.get(i).getName();
  if (i < stars.size() - 1) concatenatedStarNames += ", ";
}

然后你将文本视图的文本设置为concatenatedStarNames

【讨论】:

    【解决方案2】:

    您可以使用StringBuilder 自己构建它,例如:

    final Collection<Star> stars = models.get(position).getStars();
    final StringBuilder builder = new StringBuilder();
    boolean first = true;
    for (Star star : stars) {
        final String name = star.getName();
        if(first) {
            first = false;
            builder.append(name);
        } else {
            builder.append(", ").append(name);
        }
    }
    final String allStarNames = builder.toString();
    

    【讨论】:

      【解决方案3】:

      您可以这样做 - (使用与访问星星相同的逻辑)

      String strNames;
      
      for (int i=0; i<starsCount; i++){   //starsCount = No of stars in your JSON
          strNames += model.get(position).getStars().get(i).getName();
          if( i != starsCount-1)
              strNames += ", ";
      }
      
      textViewVariable.setText(strNames);
      

      【讨论】:

        【解决方案4】:

        这是您可能想要的正确答案, 假设您有上面的 JSON,并且您已将其转换为字符串数组。

        所以数组如下所示:

        String stars[] = {Elyes Gabel, Katharine McPhee, Robert Patrick}
        
        TextView textView = // initialise the textview here or however you do.
        
        StringBuilder builder = new StringBuilder();
        for (String star: stars) {
            builder.append(star);
            builder.append(", ");
        }
        
        textView.setText(builder.toString());
        

        你会得到想要的输出...

        【讨论】:

          猜你喜欢
          • 2018-01-23
          • 2016-04-06
          • 1970-01-01
          • 1970-01-01
          • 2021-10-24
          • 2016-12-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多