anais1477 anais1477 - 6 months ago 26
Java Question

Android : Change fragment on grid view item click

I'm trying to implement a calendar for Android. So I have a fragment which represents the calendar(a gridview) and I try to change the current fragment by clicking on an item of the grid.

So I've tried to put a setOnItemClickListener on the gridview :

public class CalendarFragment extends Fragment implements View.OnClickListener {
private GridView calendarView;
private GridCellAdapter adapter;

public View onCreateView( LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState ) {

View rootView = inflater.inflate( R.layout.fragment_calendar, container, false );

calendarView = (GridView) rootView.findViewById( );
calendarView.setOnItemClickListener( new AdapterView.OnItemClickListener() {
public void onItemClick( AdapterView<?> parent, View view, int position, long id ) {
Fragment fragment = new DayCalendarFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(, fragment )
.addToBackStack( null ).commit();

} );

adapter = new GridCellAdapter( getActivity(),, month, year );
calendarView.setAdapter( adapter );

return rootView;

But this doesn't work, I don't have any error but nothing happen when I click on it. My problem is similar to this one:

Is it possible that the adapter impact the onclick method? Can I change fragment inside the adapter class?

Answer Source

I resolved my problem by changing fragment in the onClick method of the adapter class.

Here is the code I modified :

In CalendarFragment, I removed the setOnItemClickListener and I had the FragmentManager as parameter of the adapter constuctor :

adapter = new GridCellAdapter( getActivity(),, month, year, getFragmentManager() );

In GridCellAdapter :

public void onClick( View view ) {
    fragmentManager.beginTransaction().replace(, new DayCalendarFragment() )
    .addToBackStack( null )

Thank you to those who tried to help me.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download