jar包中含有Android图片文件以及按钮等selector.xml的替代方案

来源:互联网 发布:java outofmemoryerror 编辑:程序博客网 时间:2024/05/02 05:45

jar包中含有Android图片文件以及按钮等selector.xml的替代方案

在做SDK时,需求为Jar,即图片等都必须打包进入Jar中。

经过一个上午的努力,成果如下:

1.除9.png外的资源图片 都可以打包入Jar中,并能正常解析使用。

2.由StateListDrawable来取代selector.xml实现按钮的不同点击状态的效果图。

3.总之,全部入一个Jar中,无其它文件

 

实现:

图片全部入assets目录,使用以下代码把jpg/png转为Drawable

    /**     * 读取指定asset目录中的图片文件为 Drawable     *     * @param context     * @param imageFileName     * @return null if exception happened.     */    public static Drawable getDrawableFromAssets(Context context,            String imageFileName) {        Drawable result = null;        AssetManager assetManager = context.getAssets();        InputStream is = null;        try {            is = assetManager.open(imageFileName);            result = Drawable.createFromStream(is, null);            is.close();            is = null;        } catch (IOException e) {            e.printStackTrace();        }        return result;    }

  绑定按钮的状态图片:

private void bindSelectDrawable(Context context) {        bindButtonDrawable(context, mPositiveButton, POSITVE_BTN_NORMAL_IMG,                POSITVE_BTN_PRESSED_IMG);        bindButtonDrawable(context, mNeutralButton, NEUTRAL_BTN_NORMAL_IMG,                NEUTRAL_BTN_PRESSED_IMG);        bindButtonDrawable(context, mNegativeButton, NEGATIVE_BTN_NORMAL_IMG,                NEGATIVE_BTN_PRESSED_IMG);    }

 

    /**     *     * @param context     * @param button     * @param nornalImageFileName     * @param pressedImageFileName     */    private void bindButtonDrawable(Context context, Button button,            String nornalImageFileName, String pressedImageFileName) {        StateListDrawable stateListDrawable = new StateListDrawable();        Drawable normalDrawable = ApkUtil.getDrawableFromAssets(context,                nornalImageFileName);        Drawable pressedDrawable = ApkUtil.getDrawableFromAssets(context,                pressedImageFileName);        stateListDrawable.addState(new int[] { android.R.attr.state_active },                normalDrawable);        stateListDrawable.addState(new int[] { android.R.attr.state_pressed,                android.R.attr.state_enabled }, pressedDrawable);        stateListDrawable.addState(new int[] { android.R.attr.state_focused,                android.R.attr.state_enabled }, normalDrawable);        stateListDrawable.addState(new int[] { android.R.attr.state_enabled },                normalDrawable);        button.setBackgroundDrawable(stateListDrawable);    }

  至于动态布局来取代layout.xml就不说了,比较简单。

 

原创粉丝点击