【问题标题】:attrs.getAttributeIntValue always returns default valueattrs.getAttributeIntValue 总是返回默认值
【发布时间】:2014-08-22 21:43:30
【问题描述】:

我有一些看法,并想以像素为单位获取高度。我从构造函数调用

attrs.getAttributeIntValue("http://schemas.android.com/apk/res/android", "layout_height", -1)

总是得到默认值,但是

attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "layout_height")

正常工作。 attrs.getAttributeIntValue 有什么问题?

【问题讨论】:

  • 正常工作是什么意思?你得到了什么价值?
  • 您不应该直接使用 AttributeSet,而应该使用 TypedArray,有关更多信息,请参阅 AttributeSet 文档
  • 当我从视图中获取自定义参数时,我通常使用 TypedArray,但现在我只需要“layout_height”
  • @user3165616 所以创建一个只包含一个值的 int 数组:android.R.attr.layout_height

标签: android view attr


【解决方案1】:

它返回默认值,因为layout_height 是一个字符串值。也可能是match_parentwrap_content。试试这个:

try{
    Integer.parseInt(attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "layout_height") )
}catch(NumberFormatException ex){
}

【讨论】:

  • 它不起作用,因为 getAttributeValue 返回类似“1400.0dip”的内容。我知道我可以解析这个字符串并转换为 pix,但这可能不是最好的解决方案
  • @user3165616 你不应该直接使用 AttributeSet,而应该使用 TypedArray,有关更多信息,请参阅 AttributeSet 文档
  • 当我从视图中获取自定义参数时,我通常使用 TypedArray,但现在我只需要“layout_height”
  • @user3165616 所以创建一个只包含一个值的 int 数组:android.R.attr.layout_height
  • @Vishnu 查看ViewGroup.java 源文件
【解决方案2】:

这个答案是特定于标题 attrs.getAttributeIntValue 总是返回默认值

我不确定这是否是您的情况,但值得检查以下情况

如果xml中设置的值是android:maxLength=@integer/max_name_length而不是android:maxLength="40"getAttributeIntValue总是返回默认值

这里 max_name_length 是来自资源 attrs.xml

<integer name="max_name_length">40</integer>

您可以尝试下面的代码来获取实际值

const val ANDROID_NAME_SPACE: String = "http://schemas.android.com/apk/res/android"

private fun getAndroidAttributeIntValue(
    attrs: AttributeSet?,
    attributeName: String
  ): Int {
    val value: Int?
    val stringResourceId: Int = attrs?.getAttributeResourceValue(ANDROID_NAME_SPACE, attributeName, -1) ?: -1
    value = if (stringResourceId > 0)
      resources.getInteger(stringResourceId)
    else
      attrs?.getAttributeIntValue(ANDROID_NAME_SPACE, attributeName, -1)

    return value ?: -1
  }

将其用作val maxLength = getAndroidAttributeIntValue(ANDROID_NAME_SPACE, "maxLength", -1)

<EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:maxLength="@integer/max_name_length" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多