Android gets images in drawable by reflection by name

  • 2020-05-17 06:22:33
  • OfStack

MainActivity is as follows:
 
package cn.testreflect; 
import java.lang.reflect.Field; 
import android.os.Bundle; 
import android.widget.ImageView; 
import android.app.Activity; 
/** 
* Demo describe : 
*  According to the name of the picture , Get its in by reflection drawable In the ID 
*  Based on the ID Display images  
*/ 
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"); 
} 
//$ Stands for inner class  
// so cn.testreflect.R$drawable said : 
//drawable is cn.testreflect.R The inner class  
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 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 articles: