简体   繁体   中英

How to create base class for custom views in Android using Kotlin?

I want to create a base class for all of my custom views. It can be a different type, for example, RelativeLayout or NavigationView .

So I've created abstract class with generics which is implementing the deepest class of these views which is connecting them - View . This is what I've got:

abstract class MyCustomView<VS : ViewState, V : View<VS>, P : Presenter<VS, V, *>>(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
defStyleRes: Int = 0
) : View(context, attrs, defStyleAttr, defStyleRes) { ... }

But the problem is that now I'm able to inherit only from the View . How can I build somehow generic that must be a child of the View so I could implement it and still to be able inside my base class to override methods like onAttachedToWindow ?

Try to declare your class like this:

abstract class MyCustomView<VS : ViewState, V : View<VS>, P : Presenter<VS, V, *>>() : View{ 

 constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)



(...)
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM