A Simple Way to Simultaneously Set Views and their onClick Method

In an android app, hooking up the views from their definition in a layout file to a field in a class, and setting the onClick method for the view, requires some boilerplate code that can really add up to both take time to type, and it can clutter up your code.

Roboguice can handle this to some degree with annotations, but you've still got to hook up the onClick stuff (as far as I know).

I came across this stack overflow article that provides the basis for a very very simple approach here.

Basically, you add two boilerplate methods to the class (which could of course be put in a new base activity class to simplify it further).

In the end, to both assign the view to a local field and set its onClick handler, you do this:

mYourView = getViewAndSetOnGenericOnClick(R.id.whatever);

Now, this does not combine together in one place the definition of the field itself with the binding as nice as Roboguice, but it simplifies the onClick handling, which in my experience causes most of the clutter.

Here are the two extra methods you need to add to the activity or the base activity:

 private View getViewAndSetOnGenericOnClick(int viewId) {  
  View v = findViewById(viewId);  
  //add whatever null checking you want  
   if (v!=null) {  
     v.setOnClickListener(new View.OnClickListener() 
      {  
        @Override  
         public void onClick(View v) {  
          viewClicked(v);  
         }  
      }  
   );}  
   return v;  
 }  

 private void viewClicked(View v) {  
  switch (v.getId()) {  
   case R.id.whatever:  
    doWhatEverYouWantedToDoWithThisOne();  
    break;  
   case R.id.somethingElse:  
    doSomethingElseForThisOne();  
    break;  
   default:  
  }  
 }  

Yeah, you get a big switch statement, and not all you're views are going to need an onClick method, but it's specified in one place, you don't have all that essentially repeated clutter of creating the onClick anonymous classes, and it streamlines the addition of onClick functionality when you realize you needed it after all for a particular view.

We'll see how it goes :)


No comments:

Post a Comment

Popular Posts