6

我是安卓新手。我使用以下指南在 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);

} 公共无效 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 方法中日期输出正确

4

7 回答 7

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

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

如您所见,有多种方法可以解决此问题,因此查看用户如何与您的应用程序交互以及何时需要该日期非常重要。如果您在 MainActivity 中持有对 Fragment 的引用并且您不需要尽快获得数据,则公共返回方法很好。如果您需要在用户选择日期后立即更改字符串,则静态变量很好。最后一种方法很浪费,最不推荐,但没有做静态的“魔术”。

于 2012-11-27T04:20:34.600 回答
3

尽管这是在 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;
      }
    }
  }
}
于 2017-03-19T16:35:01.617 回答
2

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

于 2013-06-05T15:55:56.273 回答
1

Here is how you can get a Date from a 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
于 2012-11-27T05:54:02.060 回答
0

使用以下代码在 onDateSet() 方法中返回 Date 类型的日期

Date date = new Date(int year, int month, int day);
于 2012-11-27T04:49:03.680 回答
0

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

于 2013-06-17T10:16:30.337 回答
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());

}

于 2019-10-01T11:42:33.260 回答