Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method defined in a ListFragment from an adapter?

I've got a ListFragment and a custom adapter.

From the adapter I get the onClick event from a button defined in the rows. In the onClick method I get some id, which I'd like to pass to the ListFragment to do some stuff.

How can I call the method showTask in the ListFragment from the adapter?

listfragment

public class TaskListFragment extends ListFragment{

    /* ... */

    @Override
    public void onCreate(Bundle savedInstanceState) {       
        super.onCreate(savedInstanceState);
        mAdapter = new TaskListAdapter(getActivity(), data);        
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) 
    {
        super.onActivityCreated(savedInstanceState);
        setListAdapter(mAdapter);
    }   

    public void showTask(long id) {

        FragmentTransaction ft = getFragmentManager().beginTransaction();

        TaskFragment taskFragment = new TaskFragment();

        Bundle args = new Bundle();
        args.putLong("id", id);
        taskFragment.setArguments(args);

        ft.replace(R.id.fragment_container, taskFragment);
        ft.commit();         
    }
}

adapter

public class TaskListAdapter extends ArrayAdapter<Task>{

    /* ... */

    private OnClickListener mOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            long id = (Integer) v.getTag();
            // how can I call showTask(id) ?
        }
    };
}
like image 724
jul Avatar asked Mar 01 '13 15:03

jul


1 Answers

A common solution is for the adapter to be an inner class of the fragment, so it can just call the method directly.

Or, pass the fragment (or some interface implemented by the fragment) to the adapter via its constructor.

like image 101
CommonsWare Avatar answered Sep 27 '22 20:09

CommonsWare