本文介绍了在片段内添加日期选择器片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在片段内创建日期选择器对话框.

I am trying to create date picker dialog inside fragment.

主要片段:

public class DataFragment extends Fragment implements
DatePickerDialog.OnDateSetListener
{
private Button addNew;

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

    String date = String.format("%02d", dayOfMonth) + "/" + String.format("%02d", monthOfYear + 1) + "/" + String.format("%02d", year);
    Log.d("DTAG", "date: "+date);
    }
}

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View RootView = inflater.inflate(R.layout.fragment_data, container, false);
    addNew = RootView.findViewById(R.id.button_add);

    addNew.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            showDatePickerDialog(view);
        }
    });

    return RootView;
}

public void showDatePickerDialog(View v)
{
    DialogFragment newFragment = new DatePickerFragment();
    newFragment.show(getFragmentManager(), "datePicker");

}

}

DatePickerFragment:

DatePickerFragment:

public class DatePickerFragment extends DialogFragment {

private DatePickerDialog.OnDateSetListener mListener;
private Context context;

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

    try {
        mListener = (DatePickerDialog.OnDateSetListener) context;
    } catch (ClassCastException e) {
        throw new ClassCastException(context.toString() + " must implement OnDateSetListener");
    }
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    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);

    // Create a new instance of DatePickerDialog and return it
   return new DatePickerDialog(context, mListener, year, month, day);
}

}

但我有一个例外:

FATAL EXCEPTION: main
 Process: michlind.com.workcalendar, PID: 4951
 java.lang.ClassCastException: michlind.com.workcalendar.views.MainActivity@a20fbb7 must implement OnDateSetListener
     at michlind.com.workcalendar.views.DatePickerFragment.onAttach(DatePickerFragment.java:29)
     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1220)
     at android.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2415)
     at android.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2194)
     at android.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2148)
     at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2049)
     at android.app.FragmentManagerImpl$1.run(FragmentManager.java:718)
     at android.os.Handler.handleCallback(Handler.java:789)
     at android.os.Handler.dispatchMessage(Handler.java:98)
     at android.os.Looper.loop(Looper.java:164)
     at android.app.ActivityThread.main(ActivityThread.java:6541)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

推荐答案

您正尝试通过 mListener 将数据从一个片段传递到另一个片段,但是 context 代表您的活动

You are trying to pass data from one fragment to another via mListener but context is representing your activity

因此出现了第二个片段的 onAttach 中的错误

hence the error in onAttach of second fragment

因为您的 MainActivity 未实现 OnDateSetListener

解决方案:您需要 实现回调机制其中

Solution : You need to implement callback mechanism where

DialogFragment ->使用接口回调

MainActivity ->使用片段实例通过调用参数为date的函数将数据发送到片段一个实例

MainActivity -> sends data to fragment one using instance of fragment by invoking it's function with parameter as date

DatePickerFragment

  • 创建接口(将由活动实现)并在 onAttach
  • 中对其进行初始化
  • 通过回调将日期值发送到mainactivity
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{

    private DatePickerFragment.OnDateReceiveCallBack mListener;
    private Context context;

    public interface OnDateReceiveCallBack {
        public void onDateReceive(int dd ,int mm, int yy);
    }

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

        try {
            mListener = (DatePickerFragment.OnDateReceiveCallBack) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString() + " must implement OnDateSetListener");
        }
    }

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        mListener.onDateReceive(dayOfMonth,monthOfYear,year);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        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);

        // Create a new instance of DatePickerDialog and return it
       return new DatePickerDialog(context, this, year, month, day);
    }

}

MainActivity

  • 实现接口回调
  • 使用函数将数据传递到 dataFragmentObject
public class MainActivity ....implements DatePickerFragment.OnDateReceiveCallBack{

    // implement callback
    public void onDateReceive(int dd ,int mm, int yy){
        dataFragmentObject.displaydate(dd,mm,yy);
    }

}

数据片段

  • 创建方法以接收数据并使用它
public class DataFragment extends Fragment
{
    private Button addNew;

    public void displaydate(int year, int monthOfYear, int dayOfMonth) {

        String date = String.format("%02d", dayOfMonth) + "/" + String.format("%02d", monthOfYear + 1) + "/" + String.format("%02d", year);
        Log.d("DTAG", "date: "+date);
        }
    }

    //..code oncreateview

    public void showDatePickerDialog(View v)
    {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getFragmentManager(), "datePicker");

    }

}

这篇关于在片段内添加日期选择器片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 08:33