In the development of Android image resources are essential, such as imageview need image resources Id,imagebutton need the ID of resources and so on, We can use R.DRAWABLE.XXX to obtain the ID of the image resource, but, at some point, it is time-consuming, we want to dynamically get the resource ID, for example, I passed a string of image name, according to the string to get the ID of the resource so it is very convenient, yes, it is very convenient, if the name of the picture is slightly Add changes, such as with img1.png,img2.png,img3.png ... This allows you to get all the IDs within a loop, and it's not as simple as a few lines of code to write less for development.
Well, let me tell you about the way to achieve it. The implementation of this method is mainly implemented using the reflection mechanism provided by Java, it must be said that the reflection mechanism is too strong, it is called the ability to use the talent to understand its benefits (I am not very useful, this is to understand a little usage, such as this article said the usage). Does not reflect the matter, I will write some of the code can be common, only need a little change can be used in their own development.
The code is as follows:
public class Mainactivity extends Activity {private ImageView mView; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); MView = (ImageView ) Findviewbyid (R.id.view); Class drawable = R.drawable.class; Field field = null;try {field = Drawable.getfield ("background"); int res_id = Field.getint (Field.getname ()); Mview.setimageresource (res_id);} catch (Exception e) {}}}
In the above code, we first get a reference to the R.drawable class and assign it to an object of class. Then generate an object of field class, according to the name of the picture can get the member variable, and then you can get the value of the member variable, that is, the ID, then you can use, is not very simple!
After my own test no problem, can normal use, if there is a problem, welcome everyone and I exchange! ^_^
Get the ID in drawable based on the image name in Android development