1

I just started to learn the fragment API on Android. I want just to send a message back to my containing activity(I did it). Now I want to clear a misunderstanding about downcasting.

Here is my fragment:

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

public class DetailFragment extends Fragment {

private EditText textFirstName, textLastName, textAge;
private FragmentListener mListener;

public DetailFragment() {
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    if (!(context instanceof FragmentListener)) throw new AssertionError();
    mListener = (FragmentListener) context;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_detail, container, false);

    textFirstName = (EditText) rootView.findViewById(R.id.textFirstName);
    textLastName = (EditText) rootView.findViewById(R.id.textLastName);
    textAge = (EditText) rootView.findViewById(R.id.textAge);

    Button doneButton = (Button) rootView.findViewById(R.id.done_button);
    doneButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            done();
        }
    });
    return rootView;
}

private void done() {
    if (mListener == null) {
        throw new AssertionError();
    }

    String firstName = textFirstName.getText().toString();
    String lastName = textLastName.getText().toString();
    int age = Integer.valueOf(textAge.getText().toString());

    mListener.onFragmentFinish(firstName, lastName, age);
}

public interface FragmentListener {
    void onFragmentFinish(String firstName, String lastName, int age);
}

}

I don't understand the downcasting here:

mListener = (FragmentListener) context;

How Context class relate to my FragmentListener interface?

I find this is contradictory to my knowledge about downcasting(Downcasting is casting to a subtype, downward to the inheritance tree.)

Hamza Belmellouki
  • 2,516
  • 1
  • 18
  • 39

1 Answers1

1

The two types, Context and FragmentListener are unrelated. However, a subclass of Context might implement the FragmentListener interface. Your onAttach() method checks that this is, in fact, what's happening and does the downcast so the FragmentListener functionality is available through the mListener member field.

Any Context (most likely an Activity) that attaches an instance of DetailFragment will need to implement DetailFragment.FragmentListener to avoid an AssertionError at run time.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521