Search code examples
androidandroid-layoutevent-driven-design

best practices for handling UI events


I have put the all the binding code for UI events on OnCreate(). It has made my OnCreate() huge.

Is there pattern around implementing UI events in android ? Can I add methods in View xml file and then I can put all the handler code somewhere else.

In a nutshell , I think I am asking how can I implement MVVM pattern with android app code ?


Solution

  • Stuff that I do:

    1. Keep all onClick functions in the XML. Avoids a lot of clutter in the Java code.
    2. Initialize event listeners as members of the activity class rather than keeping them in a function. I don't like too many curly braces in my code. Confuses the hell out of me.
    3. If my list adapters get too big I keep them in a separate class rather than as a member of the activity class and then keep all view listeners there in the adapter.
    4. To avoid creating too many onClick functions I sometimes keep one function like onNavigatonClick and then use view.getId() to see which button was clicked. As the XML is not checked for valid function calls, it leads to runtime errors if your function name is wrong.
    5. If a particular view needs a lot of UI interaction code, I create a custom view with a GestureDetector to handle UI interactions.

    I guess this is still quite basic as I haven't had much experience with Java yet.