EBurkinshaw
EBurkinshaw

Reputation: 85

Override view function android

I'm trying to support game controller input in my app, I should be able to receive the input when in focus of any element of the app. By the way it is not a game. I have tried following this guide from the android developer documentation to no avail. The problem I am facing is that I cannot override the onKeyDown function.

My only knowledge is that I need to override this function in either a custom view or activity, but this is what I am having trouble with.

Here is the sort of code I am attempting.

class customView(context:Context) : View(context){
    override fun onKeyDown(...){
        // Code to handle keydown

    }
}

I am getting an error saying something about onKeyDown not being a method of the view class (sorry I'm not at my computer at the moment so I don't know the exact error)

Just as another note I have also looked at this about custom views and I don't really understand how I should go about implementing controller input. For example if I was to create a new view, I would prefer to override something like a fragment which would allow me to have controller input across the entire app. Would it work better overriding the activity?

I'm new to android and kotlin development, so I'm sorry if this is really simple.

Thanks

Upvotes: 1

Views: 1026

Answers (1)

Tiago Oliveira
Tiago Oliveira

Reputation: 1602

You forgot the return type

class customView(context: Context) : View(context) {

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        return super.onKeyDown(keyCode, event)
    }
}

EDIT

To answer your question in the comments, in order to add this view to an XML layout your would need to do something like this

<package.of.my.costumview.customView   
    android:layout_width="match_parent"
    android:layout_height="match_parent"
/>

Upvotes: 4

Related Questions