jjyao
jjyao

Reputation: 315

Add icon before the preference

I'm doing a android app. I want to add icon before the preference. I want to add icon before the title of the inner preferencescreen, checkboxpreference,... like icon|title Thank you for your help. like that picture:

Top Android App: Quick Settings Dialogue View

Upvotes: 1

Views: 1757

Answers (4)

Yaohui.W
Yaohui.W

Reputation: 328

I'm not sure if I understood the question correct...The following code works for me, I wish it helps.

<Preference
android:key="@string/pref_style_key"
android:icon="@drawable/icon"
android:title="@string/pref_style" />

Upvotes: 4

Henrique Rocha
Henrique Rocha

Reputation: 1737

The best and easiest way to achieve what you want is to make the icon a 9-patch icon with the right border as the stretchable area.

Let's say you have an EditTextPreference that you want to add an icon before the title and summary.

You create a MyEditTextPreference class that extends EditTextPreference and override the getView method to add your 9-patch icon as the background resource.

Here is a sample code that works:

public class MyEditTextPreference extends EditTextPreference {

    public MyEditTextPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public View getView(View convertView, ViewGroup parent) {
        View view = super.getView(convertView, parent);
        view.setBackgroundResource(R.drawable.my_icon);
        return view;
    }
}

Since the icon is a 9-patch, the icon will stretch the transparent part until the right end of the cell, placing the icon on the left side.

This is a very clean solution for your problem.

Upvotes: 0

user658042
user658042

Reputation:

It's not supported out of the box, you have to extend the Preference¹ class and write your own preference UI type. But you can look at Googles implementation of the Android settings here. It's not much work to do so.

¹ "Represents the basic Preference UI building block displayed by a PreferenceActivity".

Upvotes: 0

Richard Ev
Richard Ev

Reputation: 54117

This isn't possible using the out-of-the-box PreferenceActivity (which is what I assume you're using). I think you'll need to code up your own activity for this, and manually get/set the various preferences.

Get/setting the preferences isn't as hard as it might at first sound:

// To get a preference (boolean in this example)
PreferenceManager
    .getDefaultSharedPreferences(this)
    .getBoolean("someBoolean", false);

// To set that same boolean preference to true
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = prefs.edit();
editor.putBoolean("someBoolean", true);
editor.commit();

You will need to figure out when you want to save changed preferences. I'd suggest the onPause event of your activity.

Upvotes: 0

Related Questions