168

使用新的Lint工具來對付我的代碼。它提出了很多很好的建議,但這個我不明白。如何使用複合drawable來代替包含ImageView和TextView的LinearLayout

這個標籤及其子可以通過一個和一個化合物繪製

版本來替換:檢查是否當前節點可以通過使用化合物可繪一個TextView代替。

一個的LinearLayout其中包含的ImageView和一個TextView可以作爲繪製

而且這裏的化合物來更有效地處理是我的佈局

<LinearLayout 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:orientation="horizontal" 
android:layout_centerInParent="true"> 

<ImageView 
    android:id="@+id/upImage" 
    android:layout_width="20dp" 
    android:layout_height="20dp" 
    android:layout_gravity="center_vertical" 
    android:scaleType="centerInside" 
    android:src="@drawable/up_count_big"> 
</ImageView> 

<TextView 
    android:id="@+id/LikeCount" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_marginLeft="2dp" 
    android:layout_marginBottom="1dp" 
    android:textColor="@color/gray" 
    android:textSize="16sp" 
    android:layout_gravity="center_vertical"> 
</TextView> 
</LinearLayout> 

有人可以提供如何使一個具體的例子在這種情況下可繪製的複合物?

+4

fwiw這是我通常禁用的檢查之一,因爲誤報。並非所有的'TextView'''' ImageView'組合都可以用這種方式替換。 –

+0

@RichardLeMesurier如果你想定義圖像的大小,你可以使用自定義視圖。這會讓你的視野更輕。看到我的回答: http://stackoverflow.com/a/31916731/2308720 – Oleksandr

+0

@Alex我同意在許多情況下,但是根據我的經驗,我經常不值得創建自定義視圖來解決我所考慮的問題成爲一輛越野車皮特檢查。 –

回答

224

TextView附帶4個複合可繪圖,左,右,右和底各一個。

就你而言,根本不需要LinearLayoutImageView。只需將android:drawableLeft="@drawable/up_count_big"添加到您的TextView即可。

有關更多信息,請參閱TextView#setCompoundDrawablesWithIntrinsicBounds

+26

不一定,因爲你的鏈接顯示了一個動態圖像的例子。在這種情況下,使用「ImageView」可能會更容易或更可取。警告說'可以替換爲',而​​不是'應該替換爲' –

+8

,但是如何使用XML或代碼中的DrawablePadding屬性在圖像和文本 –

+6

@Hitesh Dhamshaniya之間留出一些空間。 – Snicolas

14

如果某些原因您需要通過代碼添加,您可以使用以下代碼:

mTextView.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom); 

其中左,上,右底是可繪製

+0

需要API 17以上 – Puni

+0

我不這麼認爲,[文檔](https://developer.android.com/reference/android/widget/TextView.html)自API 1 –

+0

開始請參閱此鏈接[文檔](https ://developer.android.com/reference/android/widget/TextView.html#setCompoundDrawablesRelativeWithIntrinsicBounds(android.graphics.drawable.Drawable,android.graphics.drawable.Drawable,android.graphics.drawable.Drawable,android.graphics.drawable .Drawable)) – Puni

2

您可以使用一般複合繪製的實現,但如果你需要定義一個尺寸繪製使用這個庫:

https://github.com/a-tolstykh/textview-rich-drawable

這裏是一個小用法示例:

<com.tolstykh.textviewrichdrawable.TextViewRichDrawable 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Some text" 
     app:compoundDrawableHeight="24dp" 
     app:compoundDrawableWidth="24dp" /> 
相關問題