best practices for handling UI events

主宰稳场 提交于 2019-11-29 02:02:13

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.

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.

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.

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?

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