Kevin Baik
Kevin Baik

Reputation: 3

Android - Activity Typecasting into an Interface Type

This is code from Head First Android. Inside onAttach method, I'm wondering how the Activity activity variable is being typecast into WorkoutListListener. Is there a super-sub relationship?

public class WorkoutListFragment extends ListFragment {

public WorkoutListFragment() {
    // Required empty public constructor
}

static interface WorkoutListListener {
    void itemClicked(long id);
}

private WorkoutListListener listener;

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

    String[] names = new String[Workout.workouts.length];
    for (int i = 0; i < Workout.workouts.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);

    return super.onCreateView(inflater, container, savedInstanceState);
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    if (listener != null) {
        listener.itemClicked(id);
    }

}

@Override
public void onAttach(Activity activity) {
    super.onAttach(context);
    this.listener = (WorkoutListListener) activity;
}

}

Upvotes: 0

Views: 959

Answers (2)

danypata
danypata

Reputation: 10175

First of all that's a risky approach. The safest solution would be:

public void onAttach(Activity activity) {
    super.onAttach(context);
if(activity instanceof WorkoutListListener) {
    this.listener = (WorkoutListListener) activity;
}

}

Now what you see here is a common patter of observer that is used in android. If an activity is managing some fragments and wants to observe some events from the fragments and perform actions based on that, the activity will implement a predefined interface, the same interface that is used for casting in onAttach.

So, in your example, the activity that handles the display of the fragment will have to implement WorkoutListListener interface.

Worst case scenario WorkoutListListener is an Activity, which is a really bad name for an activity :)), then all the Activities that handles the fragment will have to subclass WorkoutListListener. (but the second option is ugly).

Upvotes: 2

Ahmed Khalaf
Ahmed Khalaf

Reputation: 1419

onAttach expects an activity reference of type Activity. That is the generic activity type of Android. However, a custom activity (such as the one in the example) may implement some interface. So, we need to cast the Activity activity reference to our custom activity type, or just cast to the interface type for the sake of the assignment (such as in the posted code).

Upvotes: 0

Related Questions