Preference myPreference;
...
Drawable originalIcon = myPreference.getIcon();
myPreference.setIcon(android.R.drawable.btn_star);
...
myPreference.setIcon(originalIcon);
The above code will change the icon to a preference, and then later restore it.
If the preference does not have an icon, the text for the preference is shifted right and the icon is added (getIcon returns null). Calling setIcon with null for the Drawable does not remove the icon. How can I remove the icon and shift the preference text left to its original position.
OK, one way to do it is to define a null icon drawable like this:
<?xml version="1.0" encoding="utf-8"?>
<layer-list />
and then use:
if (originalIcon == null) {
myPreference.setIcon(R.drawable.my_null_icon);
}
else {
myPreference.setIcon(originalIcon);
}
The problem with the accepted solution is that it still leaves spacing between the empty icon and the rest of the preference.
The proper solution is to never call setIcon(int); only call setIcon(Drawable).
Thus a slight change to your code will work:
Preference myPreference;
...
Drawable originalIcon = myPreference.getIcon();
myPreference.setIcon(mPreference.getContext().getResources().getDrawable(
android.R.drawable.btn_star));
...
myPreference.setIcon(originalIcon);
This is due to some unfortunate code in Preference.onBindView(), which falls back to the previously-set resource ID if a null drawable is passed in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With