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) ?
}
};
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With