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


原文地址:http://www.cnblogs.com/aimo/archive/2012/04/26/2472071.html  


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

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

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

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

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

 

实现:

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
  * 读取指定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;
}

  绑定按钮的状态图片:

1
2
3
4
5
6
7
8
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);
     }

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
  *
  * @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就不说了,比较简单。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值