Mortar: How-to use Presenter for List Item/Adapter

796 Views Asked by At

I using a List with Custom Adapter with ViewHolder and Item Views with Buttons. I want to handle some stuff by clicking the Buttons in a Presenter.

How can i connect a Presenter with these Item Views?

2

There are 2 best solutions below

5
Jordi Sipkens On
ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //Handle your stuff here.
    });

Something like this? Use the position to get the current item out of your List.

Buttons :

// In the adapter
Button butt = (Button) rowView.findViewById(R.id.yourbutton);
butt.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View v) {
        //Button Action.
    }
}
0
Kirill Boyarshinov On

You can use rx-android to observe AdapterView's click events the following way. It combines fine with MVP pattern used in Mortar. At first dependencies:

compile 'io.reactivex:rxjava:1.0.4'    
compile 'io.reactivex:rxandroid:0.24.0'

Then create observeClicks method in your view class.

public Observable<OnItemClickEvent> observeClicks() {
    return WidgetObservable.itemClicks(adapterView);
}

Subscribe to events in your Presenter's onLoad:

private Subscription clicks;

@Override
protected void onLoad() {
    super.onLoad();
    clicks = getView().observeClicks().subscribe(
        new Action1<OnItemClickEvent>() {
            @Override
            public void call(OnItemClickEvent event) {
                // handle click events 
            }
        }
    );
}

protected void onDestroy() {
    // unsubscribe from events
    clicks.unsubscribe();
}

Also you can do mapping OnItemClickEvent to your data inside view already and observe it instead of raw events.

public Observable<YourDataClass> observeClicks() {
    return WidgetObservable.itemClicks(adapterView).
           map(new Func1<OnItemClickEvent, YourDataClass>() {
                @Override
                public YourDataClass call(OnItemClickEvent onItemClickEvent) {
                     YourDataClass item = adapter.getItem(onItemClickEvent.position());
                     return item;
                }
           });
}

Hope this comes in handy. At least I'm doing this that way, but certainly it is not the only solution.