When and why should one use getResources()?

后端 未结 3 549
失恋的感觉
失恋的感觉 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.

提交回复
热议问题