Search code examples
androidandroid-custom-view

Is it possible to create suggestion for custom view?


I am creating a custom view but I want to show suggestions to user just like other android views. Can I do that with custom views?

For Example:

enter image description here


Solution

  • It is possible to show custom options for your custom option using enum format in your declare-styleable tag for your custom view.

    First, you declare your desired attributes in your attrs.xml file like this

    <declare-styleable name="customView">
      <attr name="customOption" format="enum">
        <enum name="option1" value="0" />
        <enum name="option2" value="1" />
      </attr>
    </declare-styleable>
    

    Now get this customOption value in your customView like this

    const val OPTION_1 = 0 //for readability
    const val OPTION_2 = 1 //for readability
    var customOption = OPTION_1
    
    init {
      paint.isAntiAlias = true
      setupAttributes(attrs)
    }
    
    private fun setupAttributes(attrs: AttributeSet?) {
      val typedArray = context.theme.obtainStyledAttributes(attrs, R.styleable.customView, 0, 0)
      customOption = typedArray.getInt(R.styleable.customView_customOption, OPTION_1.toInt())
    }