Friday, April 20, 2012

Are there problems with implementing a listener in a View subclass?

I need to subclass TextView to have it hold some additional data for me. I'm placing these new View objects into a ListView using a custom ListAdapter.



I have an action I want to perform onClick(), and it is the same action for all elements of the ListView, based on the additional data.



Would this definition, have any downsides or cause any problems?



public class UserTextView extends TextView implements OnClickListener {

public int userId;

public UserTextView(Context context) {
super(context);

this.setClickable(true);
this.setOnClickListener(this);
}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

}

}


I would expect that the code in my onClick() implementation wouldn't actually be copied, but would only exist once in memory and be called with the specific UserTextView's data. So I don't expect extra memory usage. And in fact, not having an extra Class and Object (anonymous or not) might improve performance (though not in a real, meaningful way).



If needed, the setOnClickListener() method could be invoked to change the Listener if I needed different behavior for a specific object.



It just seems to fit well into what I need:




  1. A TextView that can hold extra data (userId)

  2. A TextView class that will have the same default behavior

  3. Can be created and managed easily by a ListAdapter



I just feel that I have never seen this done this way, and am suspicious that there is something I'm missing.





No comments:

Post a Comment