如何在Android上的TextView中显示字符串列表

时间:2017-07-01 17:35:47

标签: android arrays list textview

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

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

我希望显示此名称,例如此示例:

  

Stars = Elyes Gabel,Katharine McPhee,Robert Patrick

我应该从适配器中的TextView setText

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

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

但只是告诉我 Elyes Gabel !!!

我想告诉我这样的:

  

Stars = Elyes Gabel,Katharine McPhee,Robert Patrick

我该怎么办?请帮帮我

4 个答案:

答案 0 :(得分:1)

这是您可能追求的正确答案, 假设您拥有上述JSON,并且已将其转换为String数组。

因此数组如下所示:

<id>
    tag:google.com,2013:googlealerts/feed:10407958590599670710
</id>

<title type="html">
    Uhuru&#39;s order on fare control has no legal backing
</title>

<link href="https://www.google.com/url?rct=j&sa=t&url=https://www.nation.co.ke/business/Uhuru-s-order-on-fare-control-has-no-legal-backing/996-4768072-coxlk6z/index.html&ct=ga&cd=CAIyHDI1YTNhOGJmZjY3ZmQ4NTk6Y29tOmVuOktFOlI&usg=AFQjCNG10EpkC5Gogga5T4Hkys8pg3TCHw"/>

<published>2018-09-19T18:11:15Z</published>

<updated>2018-09-19T18:11:15Z</updated>

<content type="html">
    Lawyers, matatu operators and 
    <b>NTSA</b> sources said that the transport ... transport sector — said 
    <b>NTSA</b> has no legal mandate to set fares, adding that&nbsp;...
</content>

<author>
    <name/>
</author>

您将获得所需的输出...

答案 1 :(得分:0)

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

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 :(得分:0)

您可以使用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 :(得分:0)

你可以这样做 - (以同样的方式访问星星)

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);