Home > front end >  initialize XML attributes in Custom View
initialize XML attributes in Custom View

Time:12-22

I want to create a custom ImageView with fixed height and width.
It's easy to do with XML, like

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

But how to do it programmatically?

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

CodePudding user response:

You will want to use the AppCompat version of what you want to use, such as the AppCompatImageView as layoutParams would then be supported. One thing I also saw wrong: you must specify the context and all of the included attributes in the constructor of the class:

(context : Context, attrs : AttributeSet)

These will be auto assigned by the OS so nothing really needs to be done with them, but they must be there. Here is what I have for you:

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)
    }
}

Get the current layout parameters by getting them from the base class, which would be AppCompatImageView. Then set the layout parameters to be the height and width you want as an integer.

CodePudding user response:

class CustomImageView: ImageView {
    init {    
        layoutParams.height = 20
        layoutParams.width = 20
    }
}
  • Related