給 TextView 設(shè)置 Drawable 圖片是我們最常用的需求了,但是蛋疼的是,這種設(shè)置的 Drawable 是無法調(diào)節(jié)圖片大小的,經(jīng)常不滿足我們的需求,如果我們使用 textview + imageview 來繞過去,那就顯得我們太 low 了
這里提供 2 種思路:
1. 代碼調(diào)整 Drawable 大小再傳給 TextView
這個(gè)思路很簡(jiǎn)單
TextView textView = new TextView(mContext);
Drawable drawable = getResources().getDrawable(R.drawable.icon_friend);
// 設(shè)置圖片的大小
drawable.setBounds(0, 0, 20, 20);
// 設(shè)置圖片的位置,左、上、右、下
textView.setCompoundDrawables(null, null, drawable, null);
麻煩的是我們要寫 2 行代碼,要是需求頻繁的應(yīng)該拓展一個(gè) TextView 出來,我是懶得再去寫了,需要的直接去這里 copy:TextView中DrawableXXX圖片無法設(shè)置大小的解決方案
或者可以用 TextView 自身的 API
textView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.icon, 0);
2. 使用 layer-list 圖層
layer-list 里面每個(gè)圖片資源都能設(shè)置大小,所以我們就用 layer-list 來繞一下
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:width="10dp"
android:height="10dp"
android:drawable="@drawable/logo2"/>
</layer-list>