Mastering programming with Java for Android, I encountered the following problem: I cannot read / understand an example from the book. There are two classes (heirs of AppCompatActivity and ListFragment). I can't drive in as they interact. Here is the code itself.

public class MainActivity extends AppCompatActivity implements WorkoutListFragment.WorkoutListListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //WorkoutDetailFragment fragment = (WorkoutDetailFragment) getSupportFragmentManager().findFragmentById(R.id.detail_frag); //fragment.setWorkoutId(1); } @Override public void itemClicked(long id) { WorkoutDetailFragment details = new WorkoutDetailFragment(); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); details.setWorkoutId(id); ft.replace(R.id.fragment_container, details); ft.addToBackStack(null); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.commit(); } } 

and second

 public class WorkoutListFragment extends ListFragment { public WorkoutListFragment() { // Required empty public constructor } static interface WorkoutListListener{ void itemClicked(long id); } private WorkoutListListener mListener; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { String[] names = new String[Workout.workouts.length]; for (int i = 0; i < names.length; i++){ names[i] = Workout.workouts[i].getName(); } ArrayAdapter<String> adapter = new ArrayAdapter<String>(inflater.getContext(), android.R.layout.simple_list_item_1, names); setListAdapter(adapter); // Inflate the layout for this fragment //return inflater.inflate(R.layout.fragment_workout_list, container, false); return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onAttach(Context context) { super.onAttach(context); mListener = (WorkoutListListener) context; } @Override public void onListItemClick(ListView l, View v, int position, long id) { //super.onListItemClick(l, v, position, id); if (mListener != null){ mListener.itemClicked(id); } } } 

Why when clicking on an item in the ListFragment should the code be called from the activity?

    1 answer 1

    In the onAttach method, the Context is passed - this is the Activity , it is WorkoutListListener to WorkoutListListener (which it is, as it implements this interface) and stored in the mListener field. When you click a list item, roughly speaking, the activation method is called.

    One could do this:

     @Override public void onListItemClick(ListView l, View v, int position, long id) { ((WorkoutListListener)getActivity()).itemClicked(id); } 
    • Yes. I get it now. Thank you very much! - plesser