在自定义视图中初始化 XML 个属性

initialize XML attributes in Custom View

我想创建一个具有固定高度和宽度的自定义 ImageView。
用XML就好办了,比如

<ImageView
    android:layout_width="20dp"
    android:layout_height="20dp"/>

但是如何以编程方式进行呢?

class customView : ImageView {
    // code to achieve fixed height and width
}

您将希望使用您想要使用的 AppCompat 版本,例如 AppCompatImageView,因为 layoutParams 将得到支持。我还看到错误的一件事:您必须在 class:

的构造函数中指定上下文和所有包含的属性
(context : Context, attrs : AttributeSet)

这些将由 OS 自动分配,因此实际上不需要对它们进行任何操作,但它们必须存在。这是我为您准备的:

class CustomImageView(context: Context,
    attrs : AttributeSet) : AppCompatImageView(context, attrs) {
    init {
        applyDefaults()
    }

    private fun applyDefaults(){
        val height = 130
        val width = 300
        layoutParams = ViewGroup.LayoutParams(width, height)
    }
}

通过从基础 class 获取当前布局参数,这将是 AppCompatImageView。然后设置布局参数为你想要的高度和宽度为整数。