0
\$\begingroup\$

I've recently written a Java program that displays a list of Word objects using a ListView and a custom ArrayAdapter. I also want to set an OnClickListener on the items that plays an audio file (specified in the Word class). This is the code I've written for it: WordAdapter.java:

/* Set OnClickListener on item */
    // Create MediaPlayer for the audio file
    final MediaPlayer audio = MediaPlayer.create(getContext(), currentWord.getAudioResourceId());
    // Set OnClickListener
    listItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!audio.isPlaying()) {
                audio.start();
            }
        }
    });

Is there a more efficient way to accomplish this behaviour?

\$\endgroup\$
2
\$\begingroup\$

Well it's not about performance in this case, but you could use dependency injection, which means you could pass the instance of the listener outside to the Adapter. Then just say

listItem.setOnClickListener(onClickListner); This could make your code more readable

UPDATE

Example shows, how to pass an OnClickListener outside from the class.

So, I would like to add more code, to make sure we can learn from it together:

public class Malacka{

  private OnClickListener callbackListener;

  public Malacka(OnClickListener callback){
     this.callbackListener = callback; 
  }


  public void getView(View view, int position, View parent){
    // apply viewHolder pattern here and do your stuff
   itemView.setOnClickListener(callbackListener);
  }
}
\$\endgroup\$
2
\$\begingroup\$

I'm not totally sure because you only shared small section of your code but it seems that you are creating a new click listener for every list item you have and it's a performance issue. creating new objects means more memory usage and slower code, in case of list views user may feel lacks on weaker devices. The better way to do it is to only define one click listener and assign all your list items to that. If you want to know witch item is clicked you can use tags on views. myView.setTag(whatever) and then get the tag by myView.setTag()

Also you can switch to RecyclerView. Since Android 5.0 RecyclerView can do anything a ListView or GridView can do and more with optimized performance, It also force View Recycling witch has a great effect on performance as well.

\$\endgroup\$
  • \$\begingroup\$ If I used listView.setOnItemClickListener(), would I be more efficient? \$\endgroup\$ – Larpee Sep 1 '17 at 18:24
  • \$\begingroup\$ Yes it will be better since you only define your listener once. see my updated answer about recyclerview as well. \$\endgroup\$ – Alireza A. Ahmadi Sep 2 '17 at 11:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.