Android obtains images in drawable by name through reflection

Source: Internet
Author: User

MainActivity is as follows: Copy codeThe Code is as follows: package cn. testreflect;
Import java. lang. reflect. Field;
Import android. OS. Bundle;
Import android. widget. ImageView;
Import android. app. Activity;
/**
* Demo description:
* Obtain the ID of an image in drawable through reflection based on its name.
* Display the Image Based on this ID
*/
Public class MainActivity extends Activity {
Private ImageView mImageView;
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
Init ();
}
Private void init (){
MImageView = (ImageView) findViewById (R. id. imageView );
GetImageByReflect ("yaodi ");
}
// $ Indicates the meaning of the internal class
// Therefore, cn. testreflect. R$ drawable indicates:
// Drawable is the internal class of cn. testreflect. R.
Private void getImageByReflect (String imageName ){
Try {
Field field = Class. forName ("cn. testreflect. R$ drawable"). getField (imageName );
MImageView. setBackgroundResource (field. getInt (field ));
} Catch (Exception e ){

}

}
}

Main. xml is as follows:Copy codeThe Code is as follows: <RelativeLayout
Xmlns: android = "http://schemas.android.com/apk/res/android"
Xmlns: tools = "http://schemas.android.com/tools"
Android: layout_width = "match_parent"
Android: layout_height = "match_parent"
>
<ImageView
Android: id = "@ + id/imageView"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: layout_centerInParent = "true"
/>
</RelativeLayout>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.