标签:
通过反射获取布局文件:
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);
标签:
原文地址:http://www.cnblogs.com/mada0/p/5083483.html