【问题标题】:Obtain android attr in custom view在自定义视图中获取android attr
【发布时间】:2021-02-09 12:57:16
【问题描述】:

我有一个扩展RelativeLayout 的自定义视图。我在attrs.xml 中有一些自定义属性。有没有办法像我们使用自定义属性一样获取常见的android attrs,如android:clickable

class MyView(context: Context, attributeSet: AttributeSet?): RelativeLayout(context, attributeSet) {
  init {
      val attrs = context.obtainStyledAttributes(attributeSet, R.styleable.MyView)
    
      if (attrs.getBoolean(android.R.attr.clickable, true)) {
          ...
      }
    
      attrs.recycle()
  }

}

此编译器接受,但它在运行时崩溃。有人遇到过类似的用例吗?我想避免为 SDK 中已经定义的自定义视图创建重复的属性。

【问题讨论】:

  • 通过扩展RelativeLayout,自定义视图继承了它的属性。您通常不需要“触摸”它们,除非您的意图是改变父母的行为,这实际上可能会让用户/开发人员感到困惑/不可预测。
  • 为什么会崩溃?什么是堆栈跟踪?

标签: java android xml kotlin view


【解决方案1】:

或多或少,答案一直摆在我面前。我必须理解的一件事是,当您创建样式时,它基本上是IntArray。现在,当您获取属性并传递您的样式引用时,它会根据其定义映射属性。 因此,为了获取本地属性中未声明的其他属性,例如 SDK 中的 android:,您需要将这些引用作为 IntArray 传递:

class MyView(context: Context, attributeSet: AttributeSet?): RelativeLayout(context, attributeSet) {
    init {
        val attrs = context.obtainStyledAttributes(attributeSet, intArrayOf(android.R.attr.clickable))

        if (attrs.getBoolean(0, true)) {
            ...
        }

        attrs.recycle()
    }
}

【讨论】:

    【解决方案2】:

    是的,也许这个应该可以工作

    attrs.xml 你应该这样声明

        <declare-styleable name="MyCustomView">
            <attr name="android:clickable" />
        </declare-styleable>
    

    在您的 MyCustomView 类中,您应该从类型化数组中获取所需的属性,例如:

    val clickable = typedArray.getBoolean(R.styleable.MyCustomView_android_clickable, false)
    

    【讨论】:

    • 我知道这一点。如果 SDK 中已经有这种属性,我想避免这种情况。
    • 为什么要避免它?
    • 因为我不想有重复的属性名称。如果 android:clickableapp:clickable 都代表相同的预期行为,这可能会在未来造成混淆。
    • 这一方法将允许您在声明 &lt;attr name="android:clickable" /&gt; 时拦截 android:clickable。请仔细阅读
    • 你应该只在你的视图中声明android:clickable
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-02
    相关资源
    最近更新 更多