首页 > 解决方案 > 是否可以为自定义视图创建建议?

问题描述

我正在创建一个自定义视图,但我想向用户显示建议,就像其他 android 视图一样。我可以用自定义视图做到这一点吗?

例如:

在此处输入图像描述

标签: androidandroid-custom-view

解决方案


declare-styleable可以在自定义视图的标签中使用枚举格式显示自定义选项的自定义选项。

首先,像这样在 attrs.xml 文件中声明所需的属性

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

customOption现在像这样在您的 customView 中获取此值

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())
}

推荐阅读