首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android TextView 動態設置 drawableLeft:setCompoundDrawables 需先 setBounds

     編輯:程式設計綜合問答

代碼中動態改變 TextView 的 drawableLeft,必須對 Drawable 調用 setBounds 設置寬高,否則不顯示。

正確步驟

Drawable drawable = getResources().getDrawable(R.drawable.new_icon);
// 關鍵:設置邊界,寬高可用內在尺寸
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());

// 設置左側 drawable,其他方向傳 null
textView.setCompoundDrawables(drawable, null, null, null);
// 或保留原有其他方向
// textView.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);

方法對比

方法特點
setCompoundDrawables(left, top, right, bottom)需手動 setBounds,完全控制
setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom)自動用內在尺寸,無需 setBounds,推薦
setCompoundDrawablesRelative(...)支持 RTL 佈局(start/end)

XML 靜態設置

<TextView
    android:drawableLeft="@drawable/icon"
    android:drawablePadding="8dp" />

記住 setBounds 或用 WithIntrinsicBounds 系列,drawable 才會正確顯示。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved