如何从Android中的DatePickerDialog返回日期值?

时间:2012-11-27 04:10:29

标签: android datepicker

我是android新手。我使用以下指南在android中创建了一个日期选择器。http://developer.android.com/guide/topics/ui/controls/pickers.html

 public  class DatePickerFragment extends DialogFragment
  implements DatePickerDialog.OnDateSetListener {



StringBuilder sb = new StringBuilder();
public static String date;
    @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 something with the date chosen by the user


sb.append(year);
sb.append('-');
sb.append(month+1);
sb.append('-');
sb.append(day);

date = sb.toString();
System.out.println("The date is "+date);

    }

我需要将此日期值(date = sb.toString())返回给我的MainActivity。由于onDateSet方法无效,我该怎么办?

附加信息 - DatePickerDialog在MainActivity类中触发,但不是单击按钮。单个按钮旁边有几个进程,只有在满足某些条件时才会触发日期选择器。我也不想显示日期值。只是希望它返回进行进一步处理。

欣赏任何形式的指导

更改了onDataset方法和justshow()

public void onDateSet(DatePicker view, int year, int month, int day) {

//使用用户选择的日期执行某些操作

    sb.append(year);
    sb.append('-');
    sb.append(month+1);
    sb.append('-');
    sb.append(day);

    date = sb.toString();
    MainActivity.newdate=sb.toString();
    System.out.println("The date is "+MainActivity.newdate);

}         public void justShow(){

System.out.println("The date is "+MainActivity.newdate);

}

这是与主要相关的部分(在第一次回复中建议进行更改后)

    DateToken mydate=new DateToken();
    String test=dayvals.get(0);
    DialogFragment df=new DatePickerFragment();

    if(test.equalsIgnoreCase("day")){


        df.show(getSupportFragmentManager(), "DatePik");

    }

    System.out.println("Date is on Main"+newdate);


  DatePickerFragment dpf=new DatePickerFragment();
  dpf.justShow();

newdate是静态String,但仍然输出null。在MainActivity和justShow方法中。但在onDataSet方法日期输出正确

7 个答案:

答案 0 :(得分:3)

  • 您可以在DatePickerFragment中创建一个公共方法来返回字符串。
  • 您可以在MainActivity中使用此类写入的静态变量。
  • 您可以使用SharedPreferences存储字符串。

我会选择第一个选项,如果您的应用程序是基本的,那么它是最简单的。

正如您所见,有多种方法可以解决这个问题,因此,了解用户如何与您的应用进行互动以及何时需要此日期非常重要。如果在MainActivity中保留对Fragment的引用并且不需要数据,则公共返回方法很好。 如果您在用户选择日期时需要更改字符串,则静态变量很好。 最后一种方法很浪费,最不推荐,但没有静态的“魔法”。

答案 1 :(得分:2)

在您的活动中实现一个监听器接口,并将其传递给DatePickerFragment。 然后通过调用它的方法触发监听器。 它在这里描述: http://developer.android.com/guide/topics/ui/dialogs.html#PassingEvents

答案 2 :(得分:2)

虽然这是在4年前被问到并且在1年前最后一次活动(在我的回答中)。我希望以下有所帮助。

package com.example.fragments;

import java.util.Calendar;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;

/**
 * Date picker fragment bit 18/03/2017.
 */

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

  private OnDateSetListener callbackListener;

  /**
   * An interface containing onDateSet() method signature.
   * Container Activity must implement this interface.
   */
  public interface OnDateSetListener {
    void onDateSet(DatePicker view, int year, int month, int dayOfMonth);
  }

  /* (non-Javadoc)
   * @see android.app.DialogFragment#onAttach(android.app.Activity)
   */
  @Override
  public void onAttach(Context activity) {
    super.onAttach(activity);

    try {
      callbackListener = (OnDateSetListener) activity;

    } catch (ClassCastException e) {
      throw new ClassCastException(activity.toString() + " must implement OnDateSetListener.");
    }
  }

  @NonNull
  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the current date as the default date in the picker
    final Calendar calendar = Calendar.getInstance(getResources().getConfiguration().locale);
    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH);
    int day = calendar.get(Calendar.DAY_OF_MONTH);

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

  @Override
  public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
    if (callbackListener != null) {
      callbackListener.onDateSet(view, year, month, dayOfMonth);
    }
  }
}

然后在MainActivity中执行下一步

    public class MainActivity extends AppCompatActivity implements View.OnClickListener, DatePickerFragment.OnDateSetListener {


  private EditText edittextDate;

  private Locale locale;

  private DialogFragment datePicker;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    locale = getResources().getConfiguration().locale;
    datePicker = new DatePickerFragment();

    edittextDate = (EditText) findViewById(R.id.edittextDate);
    edittextDate.setOnClickListener(this);
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {

      case R.id.edittextDate: {
        datePicker.show(getSupportFragmentManager(), "datePicker");
        break;
      }
    }
  }

  @Override
  public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
    final Calendar calendar = Calendar.getInstance(locale);
    final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);

    if (getCurrentFocus() != null) {
      switch (getCurrentFocus().getId()) {

        case R.id.edittextDate:
          calendar.set(year, month, dayOfMonth);
          edittextDate.setText(dateFormat.format(calendar.getTime()));
          break;
      }
    }
  }
}

答案 3 :(得分:1)

以下是从DatePickerDialog获取日期的方法:

private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
    // onDateSet method
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        myday = dayOfMonth;
        mymonth = monthOfYear + 1;
        myyear = year;
        date = String.valueOf(myday) + getString(R.string.iphan) + String.valueOf(mymonth) + getString(R.string.iphan) + String.valueOf(myyear);

        Log.i(TAG,"Date: "+date);
    } 
}; // DatePickerDialog.OnDateSetListener close

@Override
protected Dialog onCreateDialog(int id) {

    switch (id) {
    case DATE_DIALOG_IDdob:
        // Current Calendar Date
    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);
    return new DatePickerDialog(this, mDateSetListener, year, month, day);
    }
    return null;
} // onCreateDialog() close

答案 4 :(得分:0)

使用以下代码在onDateSet()方法中以Date-type返回日期

Date date = new Date(int year, int month, int day);

答案 5 :(得分:0)

在从DatePickerDialog类扩展的类上声明一个公共字符串varibale,并将所选日期设置为onDataSet方法内的公共字符串变量,以便您可以通过您创建的DatePickerDialog实例从MainActivity访问

答案 6 :(得分:0)

private void openCalendar() {
DatePickerDialog dialog = new DatePickerDialog(getContext(), (view, year, month, dayOfMonth) -> {

    date = getDateString(year, month, dayOfMonth);

}, mYear, mMonth, mDay);
dialog.show();

}

private String getDateString(int year, int mMonth, int mDay) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, mMonth, mDay);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
return dateFormat.format(calendar.getTime());

}