简体   繁体   English

如何从strings.xml文件在数组上插入字符串

[英]How do I insert a string on an array from the strings.xml file

How do I insert a string on an array from the strings.xml file, if I enter the following error I get the error getText(R.string.home) 如何输入来自strings.xml文件的数组中的字符串,如果输入以下错误,则会出现错误getText(R.string.home)

Error: Cannot resolve method 'getText(int)' 错误:无法解析方法“ getText(int)”

static String[] titles ={"Home",
        "Profile",
        "Settings",
        "Exit"};

You will need a Context object in order to be able to call the getString() method. 您将需要一个Context对象,以便能够调用getString()方法。 The reason you can often write simply getString(R.string.foo) rather than something like mContext.getString(R.string.foo) is that the Activity class is a subclass of Context . 您经常可以简单地编写getString(R.string.foo)而不是诸如mContext.getString(R.string.foo)之类的原因是, Activity类是Context的子类。

How exactly you get a Context object will depend on where you're trying to execute this code. 如何获得Context对象的确切方式取决于您尝试在何处执行此代码。 In a Fragment , you can write getActivity().getString(R.string.foo) . Fragment ,您可以编写getActivity().getString(R.string.foo)

you can try in this way 你可以这样尝试

 <string-array name="home">
    <item>Home</item>
    <item>Profile</item>
    <item>Settings</item>
    <item>Exit</item>
</string-array>

String [] titles= getResources().getStringArray(R.array.home);

Use getString() method as follows: 使用getString()方法,如下所示:

static String[] titles ={getString(R.string.home),
        getString(R.string.profile),
        getString(R.string.settings),
        getString(R.string.exit)};

If you are not calling this in an Activity but in a fragment, you must use getActivity().getString. 如果不是在Activity中而是在片段中调用此函数,则必须使用getActivity()。getString。 Hope that helps. 希望能有所帮助。

put you string array in like this on strings.xml file 在string.xml文件中像这样将字符串数组放入

<string-array name="menuItems">
        <item>Home</item>
        <item>Profile</item>
        <item>Settings</item>
        <item>Exit</item>
    </string-array>

Access in your java file like this 这样访问您的java文件

String [] fruitsArray= getResources().getStringArray(R.array.menuItems);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM