码迷,mamicode.com
首页 > 移动开发 > 详细

Android通过反射获取资源ID

时间:2015-12-28 20:25:45      阅读:344      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!