Home > Java > javaTutorial > How to Communicate Between a Fragment and its Adapter Using an Interface?

How to Communicate Between a Fragment and its Adapter Using an Interface?

Mary-Kate Olsen
Release: 2024-11-19 12:58:03
Original
363 people have browsed it

How to Communicate Between a Fragment and its Adapter Using an Interface?

Implementing an Interface for Communication between Fragment and Adapter

In the scenario described, you have a fragment, MyListFragment, containing a ListView and a custom CursorAdapter. You aim to notify MyListFragment when a button is pressed in a specific row of the list. To achieve this communication, you can employ an interface-based approach.

In MyListAdapter, define an interface, AdapterInterface, with a callback method, buttonPressed(), to be invoked upon button click:

public class MyListAdapter extends CursorAdapter {

    public interface AdapterInterface {
        public void buttonPressed();
    }

    ...
}
Copy after login

Next, modify MyListAdapter to include an instance variable of type AdapterInterface and a constructor that accepts an instance of this interface as an argument:

private AdapterInterface buttonListener;

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

In MyListFragment, implement AdapterInterface and override buttonPressed(), which will be invoked from the AdapterView's onClickListener in the adapter:

public MyListFragment extends Fragment implements AdapterInterface {

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

Finally, instantiate MyListAdapter within MyListFragment and pass an instance of MyListFragment itself as an argument to the adapter's constructor:

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

By doing this, MyListAdapter can invoke the buttonPressed() method of MyListFragment whenever the button in the list row is pressed. This allows for seamless communication between the adapter and the fragment, enabling you to take the necessary actions upon button click.

The above is the detailed content of How to Communicate Between a Fragment and its Adapter Using an Interface?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template