問題描述
我們從代碼里獲得Drawable在設置給View時會發現,圖片不顯示的問題.比如如下代碼:
Drawable drawable = getResources().getDrawable(R.drawable.bg_btn_green, null); btn1.setCompoundDrawables(null, drawable, null, null);//在按鍵的上部分顯示圖片
問題原因
用上面的方式代碼里獲取的drawable其實未設置setBounds()尺寸大小
解決問題
給drawable設置setBounds()就行了,如下:
drawable.setBounds(0, 0, 100, 100);
但是,這樣並沒有解決適配尺寸問題,因為這是你自己設置的固定值.這里給出2個思路來適配尺寸
第一種.如果你的drawable的xml文件是一個矢量圖(矢量圖通常有包含寬和高)或者包含內部尺寸,比如如下背景xml有提供android:width="100dp"和android:height="100dp":
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="@color/colorGreen4" /> <corners android:radius="5dp"/> <size android:width="100dp" android:height="100dp"/> </shape>
那么你就可以選擇以下方式適配尺寸:
Drawable drawable = getResources().getDrawable(R.drawable.bg_btn_green, null); // drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); btn1.setCompoundDrawables(null, drawable, null, null);//給按鍵的上部分設置一張背景圖片
drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight() 獲取內部寬度與高度
drawable.getMinimumWidth(), drawable.getMinimumHeight() 獲取推薦的最小寬度和高度
第二種.沒有內部尺寸的drawable
沒有內部尺寸的drawable一般是一個按鍵背景或者一個聊天背景框,再或者是一個分割線.這個時候我們只需要適配View的尺寸就行了.如下代碼:
btn1.post(new Runnable() { //因為View在onCreate的生命周期里被創建的時候是沒有測量尺寸的,所以我們需要將Drawable的處理放到View的列隊中 @Override public void run() { Drawable drawable = getResources().getDrawable(R.drawable.bg_btn_green, null); int width = 0; int height = 0; if (drawable.getIntrinsicWidth() == -1){ //如果是返回-1就說明沒有寬度值 width = btn1.getWidth();//獲取View的寬度 }else { width = drawable.getIntrinsicWidth(); } if (drawable.getIntrinsicHeight() == -1){ height = btn1.getHeight(); }else { height = drawable.getIntrinsicHeight(); } drawable.setBounds(0, 0, width, height); btn1.setBackground(drawable);//設置為背景 } });
如果使用drawable.getMinimumWidth(), drawable.getMinimumHeight() 則判斷的值要變成 0. 因為,這2個方法在注釋里也說明了如果沒有推薦的最小值就會返回0