【问题标题】:How Do I call String-array value in xml layout如何在 xml 布局中调用字符串数组值
【发布时间】:2015-08-08 12:28:58
【问题描述】:

我在 Android res/value 文件夹中的 string.xml 文件中有一个字符串数组,如下所示

我的字符串.xml

<string-array name="books_titles_en">
    <item>Smoking Effeccts on Your Body</item>
    <item>Smoking - effects on your body</item>
    <item>How Tobacco Smoke Causes Disease</item>
    <item>patterns of use, health effects, use in smoking cessation and regulatory issues</item>
</string-array>

我需要像这样检索数组的第一个元素

我的 home.xml

 <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:paddingLeft="@dimen/frag_1_text_pad"
                android:textSize="@dimen/frag_1_text_size"
                android:paddingRight="@dimen/frg_1_text_right_pad"
                android:id="@+id/book_link0"
                android:text="@string-array/book_title_en[0]"/>

我知道这似乎会导致错误。如何在 Android 中的 string.xml 中的字符串数组上检索这些东西

【问题讨论】:

  • 不能正常这样做。
  • 我们可以像 android:text="@string/app_name" 这样直接访问字符串,所以希望也有任何可用的方法。
  • @einschnaehkeee 我之前已经看到从字符串到数组的内容。我要求在我的另一个布局调用 home.xml 中将事物从数组获取到组件( TextView )
  • @NifrasIsmail 看到我的回答

标签: android arrays xml android-layout


【解决方案1】:

参考此链接Android - retrieve string array from resources

还有这个链接Help in getting String Array from arrays.xml file

基本上,您必须通过制作适配器来为 Java 类中的数组检索 xml 编写代码。

我发布的第一个链接使用了

for(int i = 0; i < menuArray.length; i++) 
    {
        Button b = new Button(this);
        b.setText(menuArray[i]);
        ll.addView(b);
    }

这是一个如何从 xml 中获取整个数组的示例。 您可以将其修改为单个数组值检索,或您希望检索的任何数组值。

编码愉快:D

【讨论】:

  • 没有。我需要在不使用 java 文件的情况下获取数组值。我需要从当前 xml 文件访问其他 xml 文件
【解决方案2】:

只是为了给你的问题一个完整的答案:

无法直接访问数组,但您可以这样做:

<string name="books_titles_en_1">Smoking Effeccts on Your Body</string>
<string name="books_titles_en_2">Smoking - effects on your body</string>
<string name="books_titles_en_3">How Tobacco Smoke Causes Disease</string>
<string name="books_titles_en_4">patterns of use, health effects, use in smoking cessation and regulatory issues</string>
<string-array name="books_titles_en">
    <item>@string/books_titles_en_1</item>
    <item>@string/books_titles_en_2</item>
    <item>@string/books_titles_en_3</item>
    <item>@string/books_titles_en_4</item>
</string-array>

然后:

<TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="@dimen/frag_1_text_pad"
            android:textSize="@dimen/frag_1_text_size"
            android:paddingRight="@dimen/frg_1_text_right_pad"
            android:id="@+id/book_link0"
            android:text="@string/book_title_en_1"/>

所以你基本上直接引用了你的字符串数组中引用的必要字符串。 ;)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    相关资源
    最近更新 更多