When and why should one use getResources()?

后端 未结 3 547
失恋的感觉
失恋的感觉 2021-02-03 13:45

I\'m just getting started with Android dev and playing around.

The documentation for getResources() says that it will [r]eturn a Resources instance for your applic

相关标签:
3条回答
  • 2021-02-03 14:12

    Resources have many helper methods that we may require.

    R.id, R.drawable all return dynamic int assigned by android during build time. Suppose we have a requirement where we require to access a coutries flag image based on its name.

    If we have image name as us.png and the value we have is 'us'. The 2 ways to handle it are

    if(countryName.equals("us")){
        imageview.setImageRsource(R.drawable.us);
    }
    

    OR

    Resources res = getResources();
    int imageId = res.getIdentifier(getIdentifier(countryName, "drawable"
            ,"com.myapp");
    imageview.setImageRsource(imageId);
    

    The second method will be the way to go especially when there are more than 50 countries or you will end up with a very long if-else or switch statement.

    The resources object is also used when you need to access the contents in the Assets folder

    res.getAssets().open(YOUR FILE);
    

    Resource instance can also be passed to other class files to access the the resources. These are some of the scenarios that you can use it for.

    0 讨论(0)
  • 2021-02-03 14:23

    A class that inherits Activity also inherits getResources(). If you have a class that is an Activity (or a derivative thereof) you have access to this method (via inheritance, a really, really basic concept in object oriented programming. If you have a class that isn't a derivative of such a class, you need to grant access to such a context for access to said resources.

    If you need more information about inheritance, polymorphism, or etc. regarding object oriented programming, I suggest referring to various websites or school curricula touching upon such issues.

    0 讨论(0)
  • 2021-02-03 14:24

    It will be useful in non_activity classes.

    You will pass the context to the class and from that you can access the resources.

    0 讨论(0)
提交回复
热议问题