先說下環境:res資源文件夾下有一套默認的資源圖片,另一套資源放置在asset文件夾下,保證所有圖片的名字與res資源下的圖片名字、color.xml中的顏色名稱相同。資源放置成功後,進行代碼編寫
解決辦法:
1.首先從asset文件夾中將選中、爲選中的圖片讀取出來
2.給讀到的圖片添加狀態
具體實現方式:
(1)遇到的問題,在獲取asset文件夾中獲取圖片的時,獲取圖片爲Drawable時,會導致圖片的變小,確切的來說,獲取到的drawable圖片直接顯示在高分辨率的手機上顯示很小,具體的原因在去查查
(2)解決辦法:
獲取在res文件夾下的這張默認圖片的寬、高後,按照獲取的寬高進行縮放,就解決了獲取到的圖片大小不正常的問題
//獲取res下圖片的名字
String filename =App.mContext.getResources().getResourceEntryName(resid);
//獲取在res下drawable圖片用來獲取正常的寬高發
Drawable image =App.mContext.getResources().getDrawable(resid);
int intrinsicWidth = image.getIntrinsicWidth();
int intrinsicHeight = image.getIntrinsicHeight();
//獲取asset文件夾中的drawable圖片
Drawable skinimage = Drawable.createFromStream(BarfooApp.mContext.getAssets().open(filename), null);
BitmapDrawable bd = (BitmapDrawable) skinimage;
Bitmap bm = bd.getBitmap().copy(Bitmap.Config.ARGB_8888, true);
//將asset下drawable圖片按照正常的res資源文件夾中編譯過的圖片進行設置其大小
image = new BitmapDrawable(BarfooApp.mContext.getResources(), Bitmap.createScaledBitmap(bm, intrinsicWidth, intrinsicHeight, true));
//這句是進行優化的,將設置好的圖片加入緩存(這句可忽略)
DrawableCache.getCache().put(key, image);
//進行下回收
if (bm != null && !bm.isRecycled()) {
bm.recycle();
bm = null;
}
return image;//就是我們從asset文件夾下獲取的正常skin1中的一張圖片
圖片是獲取到了,下面就是對獲取到的圖片添加狀態,因爲在asset文件夾下不能直接向在res文件夾下的一樣能夠直接設置按鈕的點觸狀態,如:按下、默認、獲取焦點等
例子:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/new" android:state_pressed="false"/>
<item android:drawable="@drawable/focusnew" android:state_pressed="true"/>
</selector>
不能向這樣在asset文件夾下直接進行設置,因爲res資源與asset資源區別在於asset資源不進行編譯,所以要是這樣寫不能直接讀取。
所以只能給從asset文件夾下的圖片手動添加這幾種狀態:
代碼如下:
// 當對應的View處於不同的狀態時,對應的bacdground跟着變化
/**
*idNormal默認狀態
idPressed 按下狀態
idFocused 獲取焦點狀態
**/
private static StateListDrawable addStateDrawable(Drawable idNormal, Drawable idPressed, Drawable idFocused) {
StateListDrawable sd = new StateListDrawable();
// 注意該處的順序,只要有一個狀態與之相配,背景就會被換掉
// 所以不要把大範圍放在前面了,如果sd.addState(new[]{},normal)放在第一個的話,就沒有什麼效果了
sd.addState(new int[] { android.R.attr.state_enabled, android.R.attr.state_focused }, idFocused);
sd.addState(new int[] { android.R.attr.state_pressed, android.R.attr.state_enabled }, idPressed);
sd.addState(new int[] { android.R.attr.state_focused }, idFocused);
sd.addState(new int[] { android.R.attr.state_pressed }, idPressed);
sd.addState(new int[] { android.R.attr.state_enabled }, idNormal);
sd.addState(new int[] {}, idNormal);
return sd;
}
在按鈕等組件設置addStateDrawable()這個方法,將asset中讀到的圖片進行設置設置其中,這個圖片的點擊效果就實現,好了,今天就先寫這個圖片的狀態,過天在寫顏色怎麼設置,就到這裏!