片段类是:
public class NewFragment extends Fragment implements onDateSetListener {
TextView tv_Date;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.my_fragment, container,
false);
return v;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tv_Date = (TextView) getView().findViewById(
R.id.tv_newDate);
tv_Date.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDatePickerDialog(v);
}
});
}
public void showDatePickerDialog(View v) {
DialogFragment fragment = new DatePickerFragment();
fragment.show(getFragmentManager(), "datePicker");
}
public void setonDate(String date, String tag) {
// TODO Auto-generated method stub
}
}
DialogFragment 代码为:
public class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
public interface onDateSetListener {
void setonDate(String date,String tag);
}
private onDateSetListener mListener;
String tag = "";
@Override
public void show(FragmentManager manager, String tag) {
// TODO Auto-generated method stub
this.tag = tag;
super.show(manager, tag);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// mListener = (OnDateSetListener) getActivity();
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
// et_HearingDate.setText((month + 1) + "/" + day + "/" + year);
mListener = (onDateSetListener) getActivity(); //Error is in this line
mListener.setonDate((month + 1) + "/" + day + "/" + year,tag);
}
}
例外:
java.lang.ClassCastException: com.example.myProject.NewActivity cannot be cast to com.example.myProject.DatePickerFragment$OnDateSetListener
新活动:
public class NewActivity extends Activity implements
onItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.case_entry_activity);
}
public void onItemSelected(String link) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Fragment fragment;
if ("New Fragment".equals(link)) {
fragment= new NewFragment();
transaction.replace(R.id.detailFragment2, fragment);
transaction.commit();
} else if ("Existing Fragment".equals(link)) {
fragment= new ExistingFragment();
transaction.replace(R.id.detailFragment2, fragment);
transaction.commit();
}
}
}