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

38. Android 反射资源工具ReflectionUtil

时间:2015-11-21 11:54:46      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

38. 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;
        }
    }
}

38. Android 反射资源工具ReflectionUtil

标签:

原文地址:http://blog.csdn.net/qq_16430735/article/details/49962997

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!