38. Android 反射资源工具ReflectionUtil

  • Android 反射资源工具ReflectionUtil
    • 工具代码
    • 工具使用

工具代码

ReflectionUtil

public class ReflectionUtil {    public enum ResourcesType {        styleable,        style,        string,        mipmap,        menu,        layout,        integer,        id,        drawable,        dimen,        color,        bool,        attr,        anim    }    /** * 根据名字,反射取得资源 * * @param context context * @param name resources name * @param type enum of ResourcesType * @return resources id */    public static int getResourceId(Context context, String name, ResourcesType type) {        String className = context.getPackageName() + ".R";        try {            Class<?> c = Class.forName(className);            for (Class childClass : c.getClasses()) {                String simpleName = childClass.getSimpleName();                if (simpleName.equals(type.name())) {                    for (Field field : childClass.getFields()) {                        String fieldName = field.getName();                        if (fieldName.equals(name)) {                            try {                                return (int) field.get(null);                            } catch (IllegalAccessException e) {                                e.printStackTrace();                            }                        }                    }                }            }        } catch (ClassNotFoundException e) {            e.printStackTrace();        }        return -1;    }}

工具使用

ReflectionUtilActivity

public class ReflectionUtilActivity extends AppCompatActivity implements View.OnClickListener {    ImageView imageView;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        this.setContentView(R.layout.activity_reflection_util);        this.imageView = (ImageView) this.findViewById(R.id.reflection_iv);        this.findViewById(R.id.reflection_bt).setOnClickListener(this);    }    /** * Called when a view has been clicked. * * @param v The view that was clicked. */    @Override    public void onClick(View v) {        switch (v.getId()) {            case R.id.reflection_bt:                /* * 获取资源名为mm_1的mipmap类型文件 */                this.imageView.setImageResource(ReflectionUtil.getResourceId(this, "mm_1", ReflectionUtil.ResourcesType.mipmap));                break;        }    }}

更多相关文章

  1. android客户端与服务端交互的工具类
  2. Android消息机制——时钟显示和异步处理工具类(AsyncTask)
  3. android studio 下载与安装
  4. 编译android
  5. 资源连接
  6. Ubuntu Android编译服务器搭建
  7. Android(安卓)关键资源的定义和使用
  8. android 细节之android.view.InflateException: Binary XML file

随机推荐

  1. My first Android(安卓)programe!
  2. android http 同步请求
  3. android 混淆时需要注意的地方
  4. android 官方的下拉刷新:SwipeRefreshLay
  5. Android(安卓)谷歌统计
  6. LinearLayout布局中将一个控件放在屏幕的
  7. Android(安卓)之 国际化与资源自适应
  8. Android(安卓)Activity跳转学习笔记
  9. Android(安卓)4.1 Jelly Bean adds Offli
  10. Android: PLEASE DO NOT USE A WAKE LOCK