在我的应用中,我有一个带有图标和文本的按钮。
<Button
...
android:drawableStart="@drawable/my_button"
android:text="ABC"
...
/>
如果条件存在,我想从代码中更改图标。
if (condition)
setIcon1()
else
setIcon2()
有什么想法吗?是的,它必须是一个按钮,否则布局将拆分。
问候
您可以尝试这种方式:
Button.setCompoundDrawablesWithIntrinsicBounds(
R.drawable.my_button,
R.drawable.my_button,
R.drawable.my_button,
R.drawable.my_button
)
我建议您查看this tutorial以获取更多详细信息。
Drawable img = getResources().getDrawable( R.drawable.profile_aadhar );
binding.btn.setCompoundDrawablesWithIntrinsicBounds( img, null, null, null);
position to set
Note setCompoundDrawablesWithIntrinsicBounds( left, top, right, bottom);
您可以这样使用它。
<Button
android:id="@+id/btn"
android:drawableStart="@drawable/my_button"
android:text="ABC"
/>
if (condition)
btn.setBackgroundResource(R.drawable.img1);
else
btn.setBackgroundResource(R.drawable.img2);
它将起作用..