Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing an icon from a preference

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.

like image 859
Steve Waring Avatar asked Oct 03 '22 19:10

Steve Waring


2 Answers

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);
}
like image 67
Steve Waring Avatar answered Oct 10 '22 13:10

Steve Waring


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.

like image 40
Stephen Talley Avatar answered Oct 10 '22 12:10

Stephen Talley