程式碼中修改TextView的DrawableLeft圖片

拭心發表於2015-06-03

先把解決程式碼貼上來:

Drawable weather = getResources().getDrawable(R.drawable.sunday);
        weather.setBounds(0, 0, weather.getMinimumWidth(), weather.getMinimumWidth());
        tv_choose_weather.setCompoundDrawables(weather, null, null, null);

/***********分割線*********************/

本來覺得在TextView中新增一個android:drawableLeft="@drawable/org3_ww0"屬性比一個ImageView+一個TextView方便多了,結果今天需要更換TextView的DrawableLeft圖片時傻眼了,遍訪名醫後方得解法,記錄如下:

TextView有個方法叫setCompoundDrawables(left,top,right,bottom)就是用來設定、修改他旁邊的圖片的,我們只需要把新的Drawable傳到對應的引數位置即可。

Drawable可以通過getResources().getDrawable(id)方法得到,例如:

Drawable weather = getResources().getDrawable(R.drawable.sunday);

你以為這就結束了?No

setCompoundDrawables() 的引數Drawable物件,必須先呼叫setBounds(int left, int top, int right, int bottom)方法,設定好這個圖片要繪製的矩形區域大小。

所以就有了解決程式碼的第二行:

weather.setBounds(0, 0, weather.getMinimumWidth(), weather.getMinimumWidth());

對了,那個setBounds的引數怎麼傳呢?

其實他讓你傳入的是四個頂點座標,然後編譯器進行運算求出矩形的長寬。我們可以直接在left、top傳入0,right、bottom傳入要繪製圖片的寬和高就行了。

相關文章