我有以下代码在 Activity 中显示日期选择器,但是当我尝试将 Activity 转换为 fragment 时,出现错误。我真的看不出代码与用于在Fragment内实现DialogFragment的解决方案相比有什么区别。

你能指出我想念的是什么吗?

MainFragment:

public class AddEntryFragment extends Fragment implements DatePickerFragment.TheListener{
    EditText datpurchased;
    public AddEntryFragment(){}

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

    @Override
    public void onStart() {
        super.onStart();
        datpurchased = (EditText) getView().findViewById(R.id.datepurchased);
        datpurchased.setOnClickListener(onClickListener);
    }

    private OnClickListener onClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch(v.getId()){
                case R.id.datepurchased:
                    showdate(v);
                break;
                default:
                break;
            }

      }
    };

    public void showdate(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        Bundle bundle = new Bundle();
        bundle.putString("dateAsText",datpurchased.getText().toString());
        newFragment.setArguments(bundle);
        newFragment.show(getFragmentManager(), "datePicker");
    }

    public void returnDate(String date) {
        datpurchased.setText(date);
    }
}

DatePickerFragment:
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
    TheListener listener;

    public interface TheListener{
        public void returnDate(String date);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState){
        Bundle bundle = getArguments();
        String date = bundle.getString("dateAsText");
        int year, month, day;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
        df.setLenient(false);
        Date d = null;
        Calendar c=Calendar.getInstance();
        try {
            d = df.parse(date);
            c.setTime(d);
        } catch (ParseException e) {
            //e.printStackTrace();
        }
        year=c.get(Calendar.YEAR);
        month=c.get(Calendar.MONTH);
        day=c.get(Calendar.DAY_OF_MONTH);
        listener = (TheListener) getActivity();
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day){
        Calendar c = Calendar.getInstance();
        c.set(year, month, day);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
        String formattedDate = sdf.format(c.getTime());
        if (listener != null)
        {
          listener.returnDate(formattedDate);

        }
    }
}

LogCat:
12-18 23:35:41.094: D/AndroidRuntime(1058): Shutting down VM
12-18 23:35:41.094: W/dalvikvm(1058): threadid=1: thread exiting with uncaught exception (group=0xb4a65b90)
12-18 23:35:41.124: E/AndroidRuntime(1058): FATAL EXCEPTION: main
12-18 23:35:41.124: E/AndroidRuntime(1058): Process: com.migrationdesk.mylibman, PID: 1058
12-18 23:35:41.124: E/AndroidRuntime(1058): java.lang.ClassCastException: com.migrationdesk.mylibman.NavContainer cannot be cast to com.migrationdesk.mylibman.DatePickerFragment$TheListener
12-18 23:35:41.124: E/AndroidRuntime(1058):     at com.migrationdesk.mylibman.DatePickerFragment.onCreateDialog(DatePickerFragment.java:41)
12-18 23:35:41.124: E/AndroidRuntime(1058):     at android.app.DialogFragment.getLayoutInflater(DialogFragment.java:398)
12-18 23:35:41.124: E/AndroidRuntime(1058):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
12-18 23:35:41.124: E/AndroidRuntime(1058):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
12-18 23:35:41.124: E/AndroidRuntime(1058):     at android.app.BackStackRecord.run(BackStackRecord.java:684)
12-18 23:35:41.124: E/AndroidRuntime(1058):     at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
12-18 23:35:41.124: E/AndroidRuntime(1058):     at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
12-18 23:35:41.124: E/AndroidRuntime(1058):     at android.os.Handler.handleCallback(Handler.java:733)
12-18 23:35:41.124: E/AndroidRuntime(1058):     at android.os.Handler.dispatchMessage(Handler.java:95)
12-18 23:35:41.124: E/AndroidRuntime(1058):     at android.os.Looper.loop(Looper.java:137)
12-18 23:35:41.124: E/AndroidRuntime(1058):     at android.app.ActivityThread.main(ActivityThread.java:4998)
12-18 23:35:41.124: E/AndroidRuntime(1058):     at java.lang.reflect.Method.invokeNative(Native Method)
12-18 23:35:41.124: E/AndroidRuntime(1058):     at java.lang.reflect.Method.invoke(Method.java:515)
12-18 23:35:41.124: E/AndroidRuntime(1058):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
12-18 23:35:41.124: E/AndroidRuntime(1058):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
12-18 23:35:41.124: E/AndroidRuntime(1058):     at dalvik.system.NativeStart.main(Native Method)

最佳答案

试试这个示例代码。

public class student extends Fragment {
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        View view= inflater.inflate(R.layout.layout_main, container, false);
        return view;
    }

    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        edittext.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    showDatePicker();
                }
            });
    }

    private void showDatePicker() {
        DatePickerFragment date = new DatePickerFragment();
        /**
        * Set Up Current Date Into dialog
        */
        Calendar calender = Calendar.getInstance();
        Bundle args = new Bundle();
        args.putInt("year", calender.get(Calendar.YEAR));
        args.putInt("month", calender.get(Calendar.MONTH));
        args.putInt("day", calender.get(Calendar.DAY_OF_MONTH));
        date.setArguments(args);
        /**
        * Set Call back to capture selected date
        */
        date.setCallBack(ondate);
        date.show(getFragmentManager(), "Date Picker");
    }

    OnDateSetListener ondate = new OnDateSetListener() {

        public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {

            edittext.setText(String.valueOf(dayOfMonth) + "-" + String.valueOf(monthOfYear+1)
               + "-" + String.valueOf(year));
        }
    };
}

创建另一个类DatePickerFragment。
public class DatePickerFragment extends DialogFragment {
    OnDateSetListener ondateSet;
    private int year, month, day;

    public DatePickerFragment() {}

    public void setCallBack(OnDateSetListener ondate) {
        ondateSet = ondate;
    }

    @SuppressLint("NewApi")
    @Override
    public void setArguments(Bundle args) {
        super.setArguments(args);
        year = args.getInt("year");
        month = args.getInt("month");
        day = args.getInt("day");
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new DatePickerDialog(getActivity(), ondateSet, year, month, day);
    }
}

10-08 03:16