How to add icons to Preference

后端 未结 9 935
一生所求
一生所求 2020-12-04 18:19

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

9条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 19:05

    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.

提交回复
热议问题