【问题标题】:Add multiple Strings to a ListArray?将多个字符串添加到 ListArray?
【发布时间】:2012-10-04 05:53:08
【问题描述】:

我有大约 70 个字符串要添加到字符串数组中。然后在 TextView 中打印字符串数组。

我做了一些功课,我想我真的想将字符串添加到 ListArray。

字符串位于 string.xml 文件中。

TextView tvHerb = (TextView) findViewById(R.id.tvHerb);

    ArrayList<String> herbList = new ArrayList<String>();
    herbList.add(R.string.angelica, null);
    herbList.add(R.string.anise_seed, null);

    tvHerb.setText(herbList.toString());

一旦布局显示在模拟器上,我就会收到运行时错误。

我迷路了!!!我也是 android 编程的新手,所以任何帮助都将不胜感激。

【问题讨论】:

    标签: android arrays string arraylist


    【解决方案1】:

    首先我同意 agreco 关于属性数量的回答。

    而且,如果您只在您的数组列表中添加来自您的字符串资源的字符串,我认为直接在您的 strings.xml 文件中定义一个字符串数组会更好。

    但是,我想您的问题来自您将 toString 应用于 ArrayList 的事实。 toString 是一种通用方法,我不确定它对数组的行为。 toString 不一定符合您的确切需求,而且大多数情况下也不符合。

    我认为你最好做这样的事情:

    String stringToInsert =herbList.get(0);
    
        for (int i=1;i<herbList.size();i++)
        {
            stringToInsert+="ANY_SEPARATOR_YOU_WANT" + herbList.get(i);
        }
    
        tvHerb.setText(stringToInsert);
    

    【讨论】:

    • 分隔符,我不认为它可能是一个新行.. 所以我将它从 TextView 更改为 ListView.. 我正在研究如何将文本获取到 listView ListView.setText 不存在。 ..
    • ListView 和 TextView 完全不同(在使用 ListView 之前花点时间阅读此内容:developer.android.com/guide/topics/ui/layout/listview.html)关于分隔符,您可以使用“\n”换行。
    【解决方案2】:

    而不是让每个字符串在 string.xml 文件中都有 id。你可以在 string.xml 中声明一个字符串数组

       `<resources>
       <string-array name="sample">
       <item>YourValue1</item>
       <item>YourValue2</item>
        .....
       <item>YourValue70</item>
       </string-array>
       </resources>`
    

    然后在你的活动中

       `String[] sample = getResources().getStringArray(R.array.sample);
       ArrayList<String> arrayList = new ArrayList<String>(sample.length);
       arrayList = Arrays.asList(sample);`
    

    【讨论】:

    • 我想要单独的字符串,这样我就可以在应用程序的其他地方调用该字符串.. 而不必知道 的位置,我可以调用herb1$ herb2$(请原谅语法)
    【解决方案3】:

    需要使用context.getString(id)获取字符串资源。

    您使用.add 的2 参数版本还有什么原因吗?

    你可能想要herbList.add( context.getString( R.string.angelica ) );

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多