How to add icons to Preference

后端 未结 9 917
一生所求
一生所求 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 18:48

    Thanks to:

    • The answer by @Tony_GPR
    • https://github.com/CyanogenMod/android_packages_apps_Settings
    • http://developer.android.com/guide/practices/ui_guidelines/icon_design.html
    • http://developer.android.com/guide/practices/ui_guidelines/icon_design_list.html
    • Scala

    The following worked for me:

    AndroidManifest.xml

    
    
        
            
                
                    
                    
                
            
        
    
    

    res/values/strings.xml:

    
    
        YOUR_APP_NAME
        About
    
    

    res/values/attrs.xml:

    
    
        
            
        
    
    

    res/layout/main.xml:

    
    
        
            
            
        
    
    

    res/layout/preference_icon.xml:

    
    
        
        
            
            
        
    
    

    Appropriately sized icons under:

    res/drawable-hdpi/YOUR_ICON.png
    res/drawable-mdpi/YOUR_ICON.png
    res/drawable-ldpi/YOUR_ICON.png
    

    AndroidMain.scala:

    class AndroidMain extends PreferenceActivity {
      override def onCreate(savedInstanceState: Bundle) {
        super.onCreate(savedInstanceState)
        addPreferencesFromResource(R.layout.main)
      }
    }
    

    IconPreference.scala:

    class IconPreference(context: Context, attrs: AttributeSet, defStyle: Int) extends Preference(context, attrs, defStyle) {
        def this(context: Context, attrs: AttributeSet) = this(context, attrs, 0)
    
        setLayoutResource(R.layout.preference_icon);
        val a: TypedArray = context.obtainStyledAttributes(attrs, R.styleable.IconPreference, defStyle, 0);
        val _icon: Drawable = a.getDrawable(R.styleable.IconPreference_icon);
    
        override def onBindView(view: View) {
            super.onBindView(view)
            val imageView: ImageView = view.findViewById(R.id.icon).asInstanceOf[ImageView]
            if (imageView != null && _icon != null) {
                imageView.setImageDrawable(_icon);
            }
        }
    }
    

提交回复
热议问题