如何在Kotlin中创建视图扩展功能

问题描述 投票:-1回答:1

我正在尝试在Kotlin中创建扩展功能。我确实尝试了一些教程,但是对如何实现这一教程却不太了解。

我正在尝试这样创建setWidth()函数

//Find my_view in the fragment
val myView = v.findViewById<RelativeLayout>(R.id.my_view)

//Then use the extension function
myView.setNewWidth(500)

这是我定义扩展功能的方式


private fun View?.setNewWidth(i: Int) {
    val layoutParams: ViewGroup.LayoutParams = View.layoutParams
    layoutParams.width = i
    View.layoutParams = layoutParams
}

我不明白我在这里需要做什么。

我想将扩展功能称为myView.ExtensionFunction(),但我不知道该怎么做。这些教程是无用的。

android kotlin android-view extension-methods kotlin-extension
1个回答
0
投票

[好,所以我的问题是我不知道如何获得对调用View的引用。即,我不知道如何调用myView并在扩展函数setNewWidth()中设置其属性

所以,我尝试使用this?并成功了。

然后,我对扩展功能做了一些更改,以使其适用于myView,即Relative Layout

这是我解决的问题:

private fun RelativeLayout?.setWidth(i: Int) {
    val layoutParams: ViewGroup.LayoutParams? = this?.layoutParams
    layoutParams?.width = i
    this?.layoutParams = layoutParams
}

© www.soinside.com 2019 - 2024. All rights reserved.