Home > Java > javaTutorial > How to Establish Communication Between a Fragment and its CursorAdapter?

How to Establish Communication Between a Fragment and its CursorAdapter?

Patricia Arquette
Release: 2024-11-12 22:10:02
Original
1016 people have browsed it

How to Establish Communication Between a Fragment and its CursorAdapter?

Creating an Interface between Fragment and Adapter

When dealing with a fragment containing a ListView and a custom CursorAdapter, establishing communication between them becomes crucial. To achieve this, interfaces can provide a clean and efficient solution.

Interface Definition

In the adapter class, define an interface that defines the method to be invoked when the button is pressed. For example:

public interface AdapterInterface {
    public void buttonPressed();
}
Copy after login

Adapter Implementation

Add a constructor to the adapter that initializes an instance variable for the interface:

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

In the bindView() method, when the button is clicked, call the buttonPressed() method on the interface:

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

Fragment Implementation

Implement the AdapterInterface in the fragment class and override the buttonPressed() method:

public class MyListFragment extends Fragment implements AdapterInterface {

    @Override
    public void buttonPressed() {
        // Custom action to be performed
    }
}
Copy after login

Initialization

When creating the adapter, pass the fragment as an argument to the constructor:

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

Notes

  • Ensure that the adapter is also recreated when the fragment is recreated to avoid referencing nonexistent objects.
  • This approach provides a clean and organized way to handle communication between the adapter and fragment.

The above is the detailed content of How to Establish Communication Between a Fragment and its CursorAdapter?. 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