![](/img/trans.png)
[英]How to change the color of vector drawable programatically in android
[英]How to add value for android drawable file for button stored in a varible programatically?
我希望使用下面的方法動態更改按鈕的圖像,並且它可以正常工作。
<Button
android:id="@+id/buttonIdDoesntMatter"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="buttonName"
android:drawableLeft="@drawable/frog"
android:onClick="listener"
android:layout_width="fill_parent">
</Button>
下面的檢索按鈕圖像的方法對我有用,其中青蛙是圖像名稱。
button.setCompoundDrawablesWithIntrinsicBounds( 0, 0, R.drawable.frog,0);
但我正在嘗試根據用戶使用共享首選項接受的選項來檢索圖像。 所以我將每個圖標名稱存儲為鍵值形式的值,並檢索用戶選擇的每個鍵的值並將它們作為文件名傳遞給 drawable。
<string-array name="pref_icon_title">
<item>camel</item>
<item>forg</item>
</string-array>
// 值對應於原始圖像名稱
</string-array>
<string-array name="pref_icon_values">
<item>camel</item>
<item>forg</item>
<item></item>
</string-array>
在檢索用戶選擇的值並將它們傳遞給 drawable 時,它給出錯誤並且不知道如何傳遞..我正在使用 String.valueOf(variable),它不起作用
不接受使用 String.valueOf 傳遞檢索到的變量。 任何建議將不勝感激。
button.setCompoundDrawablesWithIntrinsicBounds( 0, 0, R.drawable.String.valueOf(variable),0);
如果我理解得很好,您是想通過名稱獲取 drawable 的 id 嗎?
您可以使用Resource 類來實現這一點,尤其是getIdentifier函數(它將返回給定資源名稱的資源標識符)
用法
public int getIdentifier (String name,
String defType,
String defPackage)
所以在你的情況下,你應該有類似的東西:
int resourceID = getResources().getIdentifier(
variable,
"drawable",
getPackageName()
);
button.setCompoundDrawablesWithIntrinsicBounds( 0, 0, resourceID, 0);
如果您不在任何活動中,那么您必須傳遞上下文而不是資源作為參數,然后執行此操作
int resourceID = context.getResources().getIdentifier(
variable,
"drawable",
context.getPackageName()
);
button.setCompoundDrawablesWithIntrinsicBounds( 0, 0, resourceID, 0);
請注意,如果未找到此類資源,則 getIdentifier() 返回 0。 (0 不是有效的資源 ID。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.