我希望使用下面的方法動態更改按鈕的影像,并且它可以正常作業。
<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);
uj5u.com熱心網友回復:
如果我理解得很好,您是想通過名稱獲取 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。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/360245.html
上一篇:影像隱藏在按鈕android下
下一篇:即使指定了“match_parent”,使用ConstraintLayout的RecyclerView專案也不會填充整個螢屏寬度
