1616
1717package com .example .android .android_me .ui ;
1818
19+ import android .content .Context ;
1920import android .os .Bundle ;
2021import android .support .v4 .app .Fragment ;
2122import android .view .LayoutInflater ;
2223import android .view .View ;
2324import android .view .ViewGroup ;
25+ import android .widget .AdapterView ;
2426import android .widget .GridView ;
2527
2628import com .example .android .android_me .R ;
3133// The list appears as a grid of images
3234public class MasterListFragment extends Fragment {
3335
34- // TODO (1) Define a new interface OnImageClickListener that triggers a callback in the host activity
35- // The callback is a method named onImageSelected(int position) that contains information about
36- // which position on the grid of images a user has clicked
36+ // Define a new interface OnImageClickListener that triggers a callback in the host activity
37+ OnImageClickListener mCallback ;
3738
38- // TODO (2) Override onAttach to make sure that the container activity has implemented the callback
39+ // OnImageClickListener interface, calls a method in the host activity named onImageSelected
40+ public interface OnImageClickListener {
41+ void onImageSelected (int position );
42+ }
43+
44+ // Override onAttach to make sure that the container activity has implemented the callback
45+ @ Override
46+ public void onAttach (Context context ) {
47+ super .onAttach (context );
48+
49+ // This makes sure that the host activity has implemented the callback interface
50+ // If not, it throws an exception
51+ try {
52+ mCallback = (OnImageClickListener ) context ;
53+ } catch (ClassCastException e ) {
54+ throw new ClassCastException (context .toString ()
55+ + " must implement OnImageClickListener" );
56+ }
57+ }
3958
4059
4160 // Mandatory empty constructor
@@ -59,7 +78,14 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container,
5978 // Set the adapter on the GridView
6079 gridView .setAdapter (mAdapter );
6180
62- // TODO (3) Set a click listener on the gridView and trigger the callback onImageSelected when an item is clicked
81+ // Set a click listener on the gridView and trigger the callback onImageSelected when an item is clicked
82+ gridView .setOnItemClickListener (new AdapterView .OnItemClickListener () {
83+ @ Override
84+ public void onItemClick (AdapterView <?> adapterView , View view , int position , long l ) {
85+ // Trigger the callback method and pass in the position that was clicked
86+ mCallback .onImageSelected (position );
87+ }
88+ });
6389
6490 // Return the root view
6591 return rootView ;
0 commit comments