首页 > 移动平台 > 详细

Android通过反射获取资源ID

时间:2015-12-28 20:23:07      阅读:539      评论:0      收藏:0      [点我收藏+]

通过反射获取布局文件:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        int id = this.getResources().getIdentifier("layout_test", "layout", this.getPackageName());
       
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(id, null);
        
        setContentView(view);
}

使用getResources().getIdentifier(),传入三个参数:布局文件名,资源类型,包名;返回值为资源的ID。

 

使用:包名+“:”+“layout/layout_name”获取layout控件:

int id =getResources().getIdentifier(getPackageName()+":layout/layout_test",null,null);
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(id, null);
setContentView(view);

 

使用ID获取控件:

int imageViewId = getResources().getIdentifier("id_layout_test_image", "id", getPackageName());
ImageView imageView = (ImageView) findViewById(imageViewId);

 

使用图片名获取图片:

 int drawableId = getResources().getIdentifier("bjmgf_sdk_cup", "drawable", getPackageName());
 Drawable res = getResources().getDrawable(drawableId);

或者使用URI获取图片:

String uri = "@drawable/bjmgf_sdk_cup";
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
Drawable res = getResources().getDrawable(imageResource);

 

Android通过反射获取资源ID

原文:http://www.cnblogs.com/mada0/p/5083483.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!