Remove icon from 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 preference and then restore it.

If the preference does not have an icon, the text for the preference shifts to the right and the icon is added (getIcon returns null). Calling setIcon with a null value for Drawable does not remove the icon. How to remove the icon and move the preference text to its original position.

+4
source share
4 answers

OK, one way to do this is to define a null icon, which can be done as follows:

 <?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); } 
+2
source

The problem with the decision made is that it still leaves a gap between the blank icon and the rest of the preference.

The correct solution is to never call setIcon (int); only call setIcon (Drawable).

Thus, a small change in 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 unsuccessful code in Preference.onBindView (), which returns to the previously set resource identifier if empty output is passed.

+2
source

Stephen answers perfectly. I just wanted to suggest that the code might be a little shorter. Instead

 myPreference.setIcon(mPreference.getContext().getResources().getDrawable( android.R.drawable.btn_star)); 

Following work for me

 myPreference.setIcon(getActivity().getDrawable(android.R.drawable.btn.star)); 
0
source

this should do the trick.

 myPreference.setIcon(android.R.color.transparent); 
0
source

Source: https://habr.com/ru/post/1486850/


All Articles