1

I think the question says it all: I want to create a custom OnItemClickListener for a ListView. I want to add and change the parameters for a OnItemClickListener but how can I create an own so it is called if I click on an Item in the ListView?

Cilenco
  • 6,951
  • 17
  • 72
  • 152

1 Answers1

2

You create an interface first, then implement a method, where you set the listener in your custom class and already then make a main class to listen for your custom event

Interface:

public interface OnCustomEventListener{
  public void onEvent();   //can have parameters
}

method in your e.g. adapter: private OnCustomEventListener mListener; //field

//setter method
public void setCustomEventListener(OnCustomEventListener eventListener) {
   this.mListener=eventListener;
}

listener:

someObjectYouWantToHaveYourCustomListenerToBeAssignedFor.setCustomEventListener(new OnCustomEventListener(){
    public void onEvent(){
    //do whatever you want to do when the event is performed.
    }
});  

how to call e.g. from your adapter:

if(this.mListener!=null){
   this.mListener.onEvent();
}

P.S. Your custom listener may have as many parameters as you want

Source

Community
  • 1
  • 1
Boris Mocialov
  • 3,439
  • 2
  • 28
  • 55
  • Thank you for that but there is one thing I don't understand. Why does the `OnCustomEventListener` know that it should call if I click on an item? – Cilenco Aug 03 '13 at 12:59
  • because `OnCustomEventListener` acts as a callback – Boris Mocialov Aug 03 '13 at 13:02
  • I implement these three steps in my Classes but I can't recieve any ClickEvents – Cilenco Aug 03 '13 at 13:13
  • @Cilenco when do you call: `this.mListener.onEvent();` ? – Boris Mocialov Aug 03 '13 at 13:14
  • I made a class which `extands ListView`. There I put the interface `OnCustomEventListener` and the method `setCustomEventListener(OnCustomEventListener eventListener)`. In my Activity I call `myListView.setCustomEventListener(new ...)` with the event inside. – Cilenco Aug 03 '13 at 13:22
  • @Cilenco can you use `Log.i(...)` in your custom class that `extends ListView` in that part where the event should be fired to see if it is actually being fired – Boris Mocialov Aug 03 '13 at 13:24
  • I got it work a little bit. The event is fired on Activity start but not if I click on an item... – Cilenco Aug 03 '13 at 13:45
  • @Cilenco do not forget that you have to call ` this.mListener.onEvent();` every time you want your main class to know that the action got initiated – Boris Mocialov Aug 03 '13 at 13:47
  • I think my problem is that I have to fire the event from the `onTouchEvent` Method right? How can I check for a Click in this method? Or do I misunderstood something? – Cilenco Aug 03 '13 at 14:28
  • @Cilenco well, yes, i believe so, i don't know how your code looks like, so I am not sure, but yes, you should fire event when some event occurs. Firing an event: `this.mListener.onEvent();` – Boris Mocialov Aug 03 '13 at 14:30