简体   繁体   English

如何在Android中使用整数资源?

[英]How to use an integer resource in Android?

I'm trying to use an integer stored in a fikle in the values folder but something isn't woring right. 我正在尝试使用存储在values文件夹中的fikle中的整数,但有些事情并不令人满意。 Here's the xml: 这是xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="numb">5</integer>
</resources>

And here is the main activity: 以下是主要活动:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.d("testLog", R.integer.numb+"");

}

But when I run it the output is: 但是当我运行它时,输出是:

04-02 14:08:30.044: D/test(14839): 2131099648

Why do I get get 5 instead? 为什么我会得到5?

Use 采用

int value = getResources().getInteger(R.integer.numb);

For more information check the docs under the topic Integer . 有关更多信息,请查看Integer主题下的文档。

http://developer.android.com/guide/topics/resources/more-resources.html#Integer http://developer.android.com/guide/topics/resources/more-resources.html#Integer

Quoting docs 引用文档

Resources 资源

The Android resource system keeps track of all non-code assets associated with an application. Android资源系统跟踪与应用程序关联的所有非代码资产。 You can use this class to access your application's resources. 您可以使用此类访问应用程序的资源。 You can generally acquire the Resources instance associated with your application with getResources(). 您通常可以使用getResources()获取与您的应用程序关联的Resources实例。

getResources() is a method of Context . getResources()Context一种方法。

When you are accessing values from resources you need to use getResources() method like below, 当您从资源访问值时,您需要使用如下所示的getResources()方法,

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.d("testLog", getResources().getInteger(R.integer.numb) + "" );
}

Try this: 尝试这个:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.d("testLog", getResources().getInteger(R.integer.numb)+"");

}

Use in Activity: 在活动中使用:

int numb = getResources().getInteger(R.integer.numb);

Use in Fragment: 在片段中使用:

int numb = getActivity().getResources().getInteger(R.integer.numb);

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

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