Zgodni Zgodni - 4 months ago 23
Android Question

Android. Instantiating a interface?

I don't actually have a question, just want to ask you to explain me this code

public class HeadlinesFragment extends ListFragment {
OnHeadlineSelectedListener mCallback;

// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
public void onArticleSelected(int position);
}

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);

// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}

...


}

is this about a class object which implements interface's method ?
even if it is, please explain it
thanks

Answer

The code creates interface OnHeadlineSelectedListener and requires that any activity to which the fragment is attached must implement this interface. (OnHeadlineSelectedListener) activity tries to cast an activity to that interface, i.e. checks whether the activity implements it. If it does not, ClassCastException is thrown.

Comments