android - 如何访问不是init函数中成员变量的构造函数参数?

标签 android kotlin

我有一个自定义布局如下

class CustomComponent : FrameLayout {

    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        initAttrs(attrs)
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        initAttrs(attrs)
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {
        initAttrs(attrs)
    }

    init {
        LayoutInflater.from(context).inflate(R.layout.view_custom_component, this, true)
    }

    fun initAttrs(attrs: AttributeSet?) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.custom_component_attributes, 0, 0)
        my_title.text = resources.getText(typedArray
                .getResourceId(R.styleable.custom_component_attributes_custom_component_title, R.string.component_one))
        typedArray.recycle()
    }
}

现在对于每个构造函数,我必须显式调用 initAttrs(attrs)因为我找不到访问 attrs 的方法在我的 init功能。

有什么方法可以访问 attrsinit函数,所以我可以调用 initAttrs(attrs)来自 init而不是必须在每个构造函数中显式调用它?

最佳答案

使用带默认参数的构造函数:

class CustomComponent @JvmOverloads constructor(
  context: Context, 
  attrs: AttributeSet? = null, 
  defStyle: Int = 0
) : FrameLayout(context, attrs, defStyle) {

    fun init {
      // Initialize your view
    }
}

@JvmOverloads 注释告诉 Kotlin 生成三个重载的构造函数,以便它们也可以在 Java 中调用。

在您的 init 函数中,attrs 可用作可空类型:

fun init {
  LayoutInflater.from(context).inflate(R.layout.view_custom_component, this, true)

  attrs?.let {
        val typedArray = context.obtainStyledAttributes(it, R.styleable.custom_component_attributes, 0, 0)
        my_title.text = resources.getText(typedArray
                .getResourceId(R.styleable.custom_component_attributes_custom_component_title, R.string.component_one))
        typedArray.recycle()
  }
}

注意 let block 中 it 的用法。

关于android - 如何访问不是init函数中成员变量的构造函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44213958/

相关文章:

android - 在android中实现地理定位

kotlin - 检查空变量,然后在其上执行if语句

android - 数据绑定(bind)差异文本或应用

java - 如何创建 LIFO 队列 channel

android - kotlin sqlite 创建两个表

java - 如何更新 RecyclerView 中的项目?

java - XmlPullParser - 解析嵌套标记

Android - 使用指纹认证加密和解密数据

java - 使用 Espresso 测试时未在 <package> 中找到测试

java - 如何测试注入(inject)了 Koin 的 viewModel?