Zgodni Zgodni - 1 year ago 97
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);

public void onAttach(Activity 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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download