Home > Java > javaTutorial > How to Communicate Between a Fragment and its Adapter using an Event-Driven Button Click?

How to Communicate Between a Fragment and its Adapter using an Event-Driven Button Click?

DDD
Release: 2024-11-19 10:09:02
Original
586 people have browsed it

How to Communicate Between a Fragment and its Adapter using an Event-Driven Button Click?

Interfacing Fragment and Adapter through Event-Driven Button Clicks

To communicate events between a Fragment and its associated Adapter, one can implement an interface within the Adapter class. In this scenario, a Fragment named MyListFragment contains a ListView that utilizes a customized CursorAdapter. Upon button click within the list row, a notification is required to be sent to the Fragment.

The solution involves creating an interface within the Adapter class:

public class MyListAdapter extends CursorAdapter {

    public interface AdapterInterface {
        void buttonPressed();
    }

    ...
}
Copy after login

Within the Fragment class (MyListFragment), implement the AdapterInterface:

public class MyListFragment extends Fragment implements AdapterInterface {

    @Override
    public void buttonPressed() {
        // Some action
    }
}
Copy after login

To bind the Adapter and Fragment, modify the Adapter class:

public class MyListAdapter extends CursorAdapter {

    private AdapterInterface buttonListener;

    public MyListAdapter(Context context, Cursor c, int flags, AdapterInterface buttonListener) {
        super(context, c, flags);
        this.buttonListener = buttonListener;
    }

    ...
}
Copy after login

Within the Adapter's bindView method, define the button click behavior:

@Override
public void bindView(View view, Context context, Cursor cursor) {
    ...

    holder.button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            buttonListener.buttonPressed();
        }
    });
}
Copy after login

When creating the Adapter, pass the Fragment as an argument:

MyListAdapter adapter = new MyListAdapter(getActivity(), myCursor, myFlags, this);
Copy after login

This mechanism ensures that when the button is clicked, the Fragment receives the notification through the implemented interface.

The above is the detailed content of How to Communicate Between a Fragment and its Adapter using an Event-Driven Button Click?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template