anais1477 anais1477 - 28 days ago 7
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;

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

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

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

}
} );

adapter = new GridCellAdapter( getActivity(), R.id.calendar_day_gridcell, month, year );
adapter.notifyDataSetChanged();
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: https://stackoverflow.com/questions/28026219/replace-fragment-on-click-of-grid-view-item

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(), R.id.calendar_day_gridcell, month, year, getFragmentManager() );

In GridCellAdapter :

@Override
public void onClick( View view ) {
    fragmentManager.beginTransaction().replace( R.id.frame_container, new DayCalendarFragment() )
    .addToBackStack( null )
    .commit();        
}

Thank you to those who tried to help me.