I\'m making an app that extends the PreferenceActivity and I want to add an icon to each Preference.
I read a similar question, and this is the answer with more repu
After many tests and many mistakes I could get it!
I had to do this:
1 - Clone the class IconPreferenceScreen from the Android native Settings app (thanks CommonWare)
2 - Clone the layout file preference_icon.xml from the Android Settings app.
3 - Declare the IconPreferenceScreen styleable in the file attrs.xml:
4 - Declare the IconPreferenceScreen in the preference.xml file:
5 - Finally set the icon for the preference, in the preference class:
addPreferencesFromResource(R.xml.example);
IconPreferenceScreen test = (IconPreferenceScreen) findPreference("key1");
Resources res = getResources();
Drawable icon = res.getDrawable(R.drawable.icon1);
test.setIcon(icono1);
Thanks again to CommonsWare for tell me where to start, and for his explanation.
This is the cloned IconPreferenceScreen class:
package com.app.example;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
public class IconPreferenceScreen extends Preference {
private Drawable mIcon;
public IconPreferenceScreen(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public IconPreferenceScreen(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setLayoutResource(R.layout.preference_icon);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.IconPreferenceScreen, defStyle, 0);
mIcon = a.getDrawable(R.styleable.IconPreferenceScreen_icon);
}
@Override
public void onBindView(View view) {
super.onBindView(view);
ImageView imageView = (ImageView) view.findViewById(R.id.icon);
if (imageView != null && mIcon != null) {
imageView.setImageDrawable(mIcon);
}
}
public void setIcon(Drawable icon) {
if ((icon == null && mIcon != null) || (icon != null && !icon.equals(mIcon))) {
mIcon = icon;
notifyChanged();
}
}
public Drawable getIcon() {
return mIcon;
}
}
And this is the cloned preference_icon.xml layout: