使用dialogfragment从datepicker获取日期

时间:2012-07-17 16:41:28

标签: android datepicker android-dialog android-datepicker

我正在使用google示例使用dialogfragment在我的应用中插入一个日期选择器 http://developer.android.com/guide/topics/ui/controls/pickers.html

但是我不确定如何在设置之后获取日期(不是java专家)。对话框和日期选择器运行正常,我可以记录该日期是否已正确设置,但是,如何才能在父活动上执行回调?

这是我的Dialog片段

public class DatePickerFragment extends DialogFragment implements
        DatePickerDialog.OnDateSetListener {

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

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

    public void onDateSet(DatePicker view, int year, int month, int day) {
        **Log.w("DatePicker","Date = " + year);**
    }
}

...我用我的活动打电话给对话...

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

在我的父活动中调用方法而不是Log.w的正确方法是什么?我认为这与将回调作为参数或其他东西相关联,但我在互联网上找到的大多数参考文献都是关于没有对话碎片的先前版本

编辑:不确定它是否重要,但父活动被声明为:

public class EditSessionActivity extends FragmentActivity {

解决方案:感谢Lecho用户,这是实现这一目标的方法

DatePickerFragmennt.class

public class DatePickerFragment extends DialogFragment{

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

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

}

...和父活动EditSessionActivity.class ...

public class EditSessionActivity extends FragmentActivity implements OnDateSetListener {
...
    @Override
    public void onDateSet(DatePicker view, int year, int month, int day) {
        //do some stuff for example write on log and update TextField on activity
        Log.w("DatePicker","Date = " + year);
        ((EditText) findViewById(R.id.tf_date)).setText("Date = " + year);
    }

9 个答案:

答案 0 :(得分:63)

DatePickerDialog的构造函数将DatePickerDialog.OnDateSetListener作为第二个参数,因此您可能应该在父活动EditSessionActivity(而不是DatePickerFragment)中实现该接口并更改此行:

return new DatePickerDialog(getActivity(), this, year, month, day);

进入这个:

return new DatePickerDialog(getActivity(), (EditSessionActivity)getActivity(), year, month, day);

然后你的活动应该是这样的:

public class EditSessionActivity extends FragmentActivity implements
        DatePickerDialog.OnDateSetListener{

    public void onDateSet(DatePicker view, int year, int month, int day) {
        //use date in your activity
    }
    ...
}

答案 1 :(得分:25)

我在我的类中创建日期选择器时简单地覆盖onDateSet,显示日期选择器。 请参阅以下代码:

  private OnClickListener onDateClicked() {
    return new OnClickListener() {
          @Override
          public void onClick(View v) {
             DialogFragment newFragment = new DatePickerFragment() {
                @Override
                public void onDateSet(DatePicker view, int year, int month, int day) {
                  salePaymentCustomView.setBtDateText("" + day + "/" + month+1 + "/" + year);
                }
             };
             newFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
    }
  };
 } 

答案 2 :(得分:13)

也可以在不将onDateSet方法移动到父活动的情况下解决问题。您只需告诉DatePickerFragment搜索视图的位置:

public class DatePickerFragment extends DialogFragment implements
    DatePickerDialog.OnDateSetListener {

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

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

    public void onDateSet(DatePicker view, int year, int month, int day) {
        // do some stuff for example write on log and update TextField on activity
        Log.w("DatePicker","Date = " + year);
        ((TextView) getActivity().findViewById(R.id.tf_date)).setText("Date = " + year);
    }
}

我还将演员的目标从EditText更改为TextView。这样,您可以将您的实现重用于不同类型的视图,而不仅仅是EditText

答案 3 :(得分:9)

我对上述答案进行了一次更正。 而不是像这样返回DatePickerDialog

  

返回新的DatePickerDialog(getActivity(),(EditSessionActivity)getActivity(),年,月,日);

你应该以更通用的方式返回它

  

返回新的DatePickerDialog(getActivity(),(OnDateSetListener)getActivity(),年,月,日);

确保您的活动实现OnDateSetListener接口并覆盖函数onDateSet

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

答案 4 :(得分:3)

public void onDate(View view) {

        DialogFragment fragment = new SelectDateFragment();
        fragment.show(getFragmentManager(), "Date Picker");
    }

//  @SuppressLint("NewApi")
    class SelectDateFragment extends DialogFragment implements
            DatePickerDialog.OnDateSetListener {

        public Dialog onCreateDialog(Bundle savedInstanceState) {


            System.out.println("entrering on create dialog");;

            return new DatePickerDialog(getActivity(), this, mYear, mMonth,
                    mDay);//it will return dialog setting date with mYera,MMonth and MDay

        }

        @Override
        public void onDateSet(android.widget.DatePicker view, int year,
                int monthOfYear, int dayOfMonth) {
            System.out.println("year=" + year + "day=" + dayOfMonth + "month="
                    + monthOfYear);
            mYear=year;
            mMonth=monthOfYear;
            mDay=dayOfMonth;

            onPopulateSet(year, monthOfYear + 1, dayOfMonth);

        }
// set the selected date in the edit text  
        private void onPopulateSet(int year, int i, int dayOfMonth) {
            EditText et_setDate;
            et_setDate = (EditText) findViewById(R.id.register_et_dob);//register_et_dob:-id name of the edit text 
            et_setDate.setText(dayOfMonth + "/" + i + "/" + year);
            System.out.println("enetring on populate Set");

        }

答案 5 :(得分:2)

Leszek的回答有效,但如果Dialog是从另一个Fragment启动的话,则不行。在这种情况下,您需要在创建对话框的代码中使用setTargetFragment(),并在对话框代码中使用getTargetFragment()

在创建对话框的代码中:

DialogFragment dialogFragment = new YourDialogFragment();
dialogFragment.setTargetFragment(YourParentFragment.this, 0);
dialogFragment.show(getFragmentManager(), "mydialog");

在DialogFragment代码中:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
    DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener()
    {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
        {
            YourParentFragment parentFragment = (YourParentFragment) getTargetFragment();
            // Manipulate the parent fragment
            // ...
        }
    };
    // Get the initial date
    // ...
    return new DatePickerDialog(getActivity(), listener, year, month, day);
}

答案 6 :(得分:2)

如果你必须将结果返回到片段而不是活动,这是一个完整的解决方案:

final Calendar c = Calendar.getInstance();
DatePickerDialogFragment datePicker = DatePickerDialogFragment.newInstance(
        c.get(Calendar.YEAR),
        c.get(Calendar.MONTH),
        c.get(Calendar.DAY_OF_MONTH));
datePicker.setListener(this);
datePicker.show(getChildFragmentManager(), null);

然后只需在片段或活动中使用它:

{{1}}

答案 7 :(得分:0)

我遇到了类似的问题,但我的日期选择器是从另一个片段中的对话框片段启动的。这使得回调很难,因为他们想要返回主活动,我希望数据返回到前一个对话框片段。

最初,我将新的日期值传递给Main Activity(使用OnDateSetListener),然后使用启动日期选择器的对话框获取它们,但是当datepicker关闭时,在该对话框中没有触发生命周期事件。

我得到的结果是在日期选择器中的onDismiss中,实例化一个新的对话框片段,在其上调用set results方法然后启动它。当然,为此,您需要确保在启动日期选择器时解除之前的片段。

这是调用日期选择器

的dialogFragment
public class NewTrialDialogFragment extends DialogFragment  {

public final String LOG_TAG = "NewTrialDialog Fragment";

Button startDateButton;
Integer newYear, newMonth, newDay;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.dialog_new_trial, container, false);
    getDialog().setTitle("Dialog New Trial");

    startDateButton = (Button) rootView.findViewById(R.id.button_start_date);
    startDateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showDatePickerDialog(v);
        }
    });

    //If you exit the datepicker without choosing anything, it returns zeros
    if (newYear != null && newMonth != null && newDay != null && newYear != 0) {
        startDateButton.setText(newYear + " " + newMonth + " " + newDay);
    }else{
        startDateButton.setText("Select Start Date");
    }

     return rootView;
}

public void showDatePickerDialog(View v) {
    TrialDatePickerDialog newDialog = new TrialDatePickerDialog();
    newDialog.show(getActivity().getSupportFragmentManager(), "datePicker");
    this.dismiss();
}

public void setDates(int year, int month, int day){
    newYear = year;
    newMonth = month;
    newDay = day;
}}

日期选择器

public  class TrialDatePickerDialog extends DialogFragment implements DatePickerDialog.OnDateSetListener
     {

private final String LOG_TAG = "TrialDatePickerDialog";
int newYear, newMonth, newDay;


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

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

         @Override
         public void onDismiss(DialogInterface dialog) {
             super.onDismiss(dialog);
             FragmentManager fm = getActivity().getSupportFragmentManager();
             NewTrialDialogFragment newTrialDialogFragment = new NewTrialDialogFragment();
             newTrialDialogFragment.setDates(newYear, newMonth, newDay);
             newTrialDialogFragment.show(fm, "new_trial_dialog");

         }

         @Override
         public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
             newYear = year;
             newMonth = monthOfYear;
             newDay = dayOfMonth;
         }
     }

答案 8 :(得分:0)

科特林版本。

DatePickerFragment类:

class DatePickerFragment : DialogFragment() {

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

        val c = Calendar.getInstance()
        val year = c.get(Calendar.YEAR)
        val month = c.get(Calendar.MONTH)
        val day = c.get(Calendar.DAY_OF_MONTH)

        return DatePickerDialog(context!!, context!! as MainActivity, year, month, day)
    }
}

DatePickerDialog.OnDateSetListener 已移至MainActicity

class MainActivity : AppCompatActivity(), DatePickerDialog.OnDateSetListener {

    ..

    override fun onDateSet(view: DatePicker, year: Int, month: Int, day: Int) {
        //use date in your activity
    }
}