我刚开始在Android上学习fragment API。
我只想给我的包含活动发一条消息(我做了)。现在我想澄清一个关于下压的误解。
这是我的片段:
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);
}
}
我不理解这里的贬低:
mListener = (FragmentListener) context;
上下文类如何与我的FragmentListener接口相关?
我发现这与我对向下投射(向下投射是投射到子类型,向下投射到继承树)的了解是矛盾的。