VincentTheonardo VincentTheonardo -4 years ago 89
Android Question

How to communicate with fragment from my adapter class

I have created a custom adapter class. In that class, I have a code that will have to send a message to my fragment, when I clicked on my listview layout.
After googling, the best approach to do it may be using interface. Most of them are the example of communicating between activity with the fragment. But in my case, I don't have any ideas about how to communicate between my adapter class with my fragment class.
let says I create an interface in my adapter class like:

public interface SuccessResponse{
void onSuccess();
}


and on the LinearLayout inside my adapter class I want it to be something like:

linearLayout.setOnClickListener(new View.OnClickListener{
@Override
public void onClick (View view){
SuccessResponse.onSuccess();
}
})


Then I want to make sure my fragment page get the onSuccess() method and do something like :

public class MyFragment extends ListFragment implements Adapter.SuccessResponse{
@Override
public void onSuccess(){
//do Something
}
}


Is there any way to do something like above?

Answer Source

The following code may help you.

public class ExampleFragment extends Fragment implements MyAdapter.SuccessResponse{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View contentView  = inflater.inflate(R.layout.my_layout, container, false);
        MyAdapter myAdapter = new MyAdapter(getActivity(), 0);
        myAdapter.successResponse = this;
        return contentView;
    }

    @Override
    public void onSuccess() {

    }
}

class MyAdapter extends ArrayAdapter{
    SuccessResponse successResponse;

    public MyAdapter(Context context, int resource) {
        super(context, resource);
    }

    public interface SuccessResponse{
        void onSuccess();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //ur views
        linearLayout.setOnClickListener(new View.OnClickListener{
            @Override
            public void onClick (View view){
                if(successResponse!=null)
                    successResponse.onSuccess();
            }
        })
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download