best practices for handling UI events

こ雲淡風輕ζ 提交于 2019-12-18 03:38:06

问题


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 ?


回答1:


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.




回答2:


In 1.6 and later you can specify onClick methods in your layout XML file to trim a bit of the fat. I generally just hide it all away in a initUi() method that I have my onCreate method call. This way at least the onCreate is easier to read.




回答3:


Lots of good answers to this already. :)

If you're using Android 1.6 or later you might find the new fragments API helpful for organizing and partitioning your activities into several logical units.




回答4:


onCreate is usually the best place for calling setContentView and setting up listeners, but the code for handling the user interractions normally goes in onClick, onTouch, onKey etc. routines.

Maybe if you posted your code we could see what you've done?



来源:https://stackoverflow.com/questions/5851418/best-practices-for-handling-ui-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!