开发者

How to get a value of a string resource in constants file?

i am working on an application where i have to get a value of string resource to a constant. how can i do that? any ideas please开发者_开发百科.

The String is placed in

Application/res/values/strings.xml

and the name of the resource is let say app_version. now i want to get this app version to a constant string in another file. Any help is appreciated.


Try context.getResources().getString(R.string.app_version) where 'context' is your Activity or Application instance.

If your question is really about getting the version name of your application there is a better way:

String versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;

This way you retrieve the info directly from the AndroidManifest and you don't have to maintain it twice.


In Java: R.string.string_name 
In XML:@string/string_name

R.string.app_version or @string/app_version taken from strings.xml is your constant and will always represent the value you entered into that XML file.

  • http://developer.android.com/guide/topics/resources/string-resource.html


All responses here aren't up to date. This is the right way to do it. Better to use

@StringRes

public class AndroidClass{
...
    @StringRes
    private static final int[] TAB_TITLES = new int[]{R.string.tab1, R.string.tab2, R.string.tab_2};

 private final Context mContext;
...


     public CharSequence getString(int position) {
         return mContext.getResources().getString(TAB_TITLES[position]);
     }
}


I wanted to do this as well, but upon reflection, I'm not sure this is possible. We are trying to set a value at compile time that is not available until run time.

Constants are set at compile time. Now, the resource ID is available then, but the value, which Android can change by locale, is not. Therefore, the string value is not available until runtime.

My workaround was to make a public static value, and assign it if it is null, to the string value at create time. I probably should've just used a plain old instance variable, but this works. Although, you can overwrite the value.

public class MyFragment 
...    
    public static String SHOW_FOO;
...

    public View onCreateView(...
    if (SHOW_FOO == null) {
        SHOW_FOO = getResources().getString(R.string.settings_foo_key);
    }
....
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜