在资源文件中存放有 image_1.png, image_2.png, image_3.png 三张图片 , 根据传入参数动态引用对应的图片 , 有三个解决方法
根据R.drawable.xx动态引用是错误的 , 因为每个这种id都对应着R文件中的一个id,如果没有相对应的id , 编译不会通过;
建立一个工程,包名为com.yun.demo
方案一 : 图片放在drawable目录下的情况
[java] view plaincopy
- Resources resources = this.getResources();
- int imageIndentify = resources.getIdentifier(imageName, "drawable","chao.yun.demo");
使用上面的代码可以通过字符串拼接图片名称 , 根据传入的参数 , 拼接imageName字符串 , 从而动态的获取图片对应的id;
[java] view plaincopy
- resources.getIdentifier(imageName, "drawable","chao.yun.demo");
这个方法返回的是图片对应的id ;
第一个参数是图片的名称 , 如果没有找到 , 返回0 ;
第二个参数是默认的资源类型 , 如果找的是图片 , 就是 "drawable" , 这个不是具体的目录 , 因此不用注明"drawable-hdpi"
第三个参数是包名 , 这个包名是创建工程时候的包名 , 是总的包名 , 与manifest配置文件中的包名相同;
详细代码 :
layout中的代码 :
[html] view plaincopy
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
- <LinearLayout
- android:id="@+id/ll_1"
- android:layout_width="fill_parent"
- android:layout_height="0px"
- android:layout_weight="1"></LinearLayout>
- <LinearLayout
- android:id="@+id/ll_2"
- android:layout_width="fill_parent"
- android:layout_height="0px"
- android:layout_weight="1"></LinearLayout>
- <LinearLayout
- android:id="@+id/ll_3"
- android:layout_width="fill_parent"
- android:layout_height="0px"
- android:layout_weight="1"></LinearLayout>
- </LinearLayout>
activity代码 :
[java] view plaincopy
- public class MainActivity extends Activity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- LinearLayout ll_1 = (LinearLayout) findViewById(R.id.ll_1);
- LinearLayout ll_2 = (LinearLayout) findViewById(R.id.ll_2);
- LinearLayout ll_3 = (LinearLayout) findViewById(R.id.ll_3);
- Resources resources = this.getResources();
- String imageName = "image_" + 1;
- int imageIndentify = resources.getIdentifier(imageName, "drawable","chao.yun.demo");
- ll_1.setBackgroundResource(imageIndentify);
- imageName = "image_" + 2;
- imageIndentify = resources.getIdentifier(imageName, "drawable","chao.yun.demo");
- ll_2.setBackgroundResource(imageIndentify);
- imageName = "image_" + 3;
- imageIndentify = resources.getIdentifier(imageName, "drawable","chao.yun.demo");
- ll_3.setBackgroundResource(imageIndentify);
- }
- }