当前位置: 首页 > 知识库问答 >
问题:

如何在Android DatePickerDialog中放置以前选择的日期?

慎峻
2023-03-14
partial Fragment file:

import android.content.DialogInterface;
import android.support.v4.app.DialogFragment;
import android.app.Dialog;
import android.app.DatePickerDialog;
import android.view.inputmethod.InputMethodManager;
import android.os.Bundle;
import android.widget.DatePicker;
import android.widget.EditText;
import java.util.Calendar;

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

private EditText txtDate;
private int currentyear;
private int currentmonth;
private int currentday;
private int prvselectedyear;
private int prvselectedmonth;
private int prvselectedday;

private String stringDueDateFrag;

public DatePickerFragment() {
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    txtDate = (EditText) getActivity().getWindow().getDecorView().getRootView().findViewById(R.id.FEditText);

    // If the FEditText line is empty (no "Due Date") entered then add current date to a new DatePickerDialog.
    if (txtDate.getText().length() == 0) {
    // DatePickerDialog is a simple dialog containing a DatePicker.
    // Set up a Calendar object that will capture the current date for the DatePickerDialog to use.
    // Use the current date as the default date in the DatePicker.
    final Calendar cal = Calendar.getInstance();
    currentyear = cal.get(Calendar.YEAR);
    currentmonth = cal.get(Calendar.MONTH);
    currentday = cal.get(Calendar.DAY_OF_MONTH);

    // Create a new instance of DatePickerDialog by passing 5 parameters/arguments to the constructor and return it.
    DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, currentyear, currentmonth, currentday);
    dialog.getDatePicker().setCalendarViewShown(true);
    dialog.getDatePicker().setSpinnersShown(false);
    dialog.setTitle("Select a Due Date");

    return dialog;
    }

    // If the FEditText line already has a due date then put the user's previously selected date in
    // the DatePickerDialog to edit.
    else {
       final Calendar prvcalendar = Calendar.getInstance();
       prvselectedyear = prvcalendar.get(Calendar.YEAR);
       prvselectedmonth = prvcalendar.get(Calendar.MONTH);
       prvselectedday = prvcalendar.get(Calendar.DAY_OF_MONTH);

       // Create a new instance of DatePickerDialog by passing 5 parameters/arguments to the constructor and return it.
       DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, prvselectedyear, prvselectedmonth, prvselectedday);
       dialog.getDatePicker().setCalendarViewShown(true);
       dialog.getDatePicker().setSpinnersShown(false);
       dialog.setTitle("Select a Due Date");

       return dialog;
    }
}

public void onDateSet (DatePicker view,int year, int month, int day) {
    txtDate = (EditText) getActivity().getWindow().getDecorView().getRootView().findViewById(R.id.FEditText);
    stringDueDateFrag = (month + 1) + "/" + day + "/" + year + " ";
    txtDate.setText(stringDueDateFrag);
    txtDate.setSelection(txtDate.getText().length());

    // Set up a Calendar object to capture the user selected date in case the user wants
    // edit the date later.  Put the user selected date in a Bundle for onCreateDialog function to use.
    Calendar prvcalendar = Calendar.getInstance();
    Bundle argsbundle = new Bundle();
    argsbundle.putInt("year", prvcalendar.get(Calendar.YEAR));
    argsbundle.putInt("month", prvcalendar.get(Calendar.MONTH));
    argsbundle.putInt("day", prvcalendar.get(Calendar.DAY_OF_MONTH));
    setArguments(argsbundle);
}
public class Activity extends AppCompatActivity {

private ListenerEditText fListenerEditText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.cardviewinput);

    fListenerEditText = (ListenerEditText) findViewById(R.id.FEditText);

    fListenerEditText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DialogFragment newFragment = new DatePickerFragment();
            newFragment.show(getSupportFragmentManager(), "datePicker");
        }
    });

    fListenerEditText.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus && (fListenerEditText.getText().length() == 0)) {
                DialogFragment newFragment = new DatePickerFragment();
                newFragment.show(getSupportFragmentManager(), "datePicker");
            }
        }
    });

以下是Android Studio的异常输出:

09-19 03:18:43.052  17379-17379/com.example.jdw.fourthscreen W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xa6310288)
09-19 03:18:43.052  17379-17379/com.example.jdw.fourthscreen E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.IllegalStateException: Fragment already active
            at android.support.v4.app.Fragment.setArguments(Fragment.java:551)
            at com.example.jdw.fourthscreen.DatePickerFragment.onDateSet(DatePickerFragment.java:100)
            at android.app.DatePickerDialog.tryNotifyDateSet(DatePickerDialog.java:148)
            at android.app.DatePickerDialog.onClick(DatePickerDialog.java:116)
            at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4745)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)

共有1个答案

严令秋
2023-03-14

当您的edittext为空并单击它时,将显示对话框两次。第一个在onclick()方法中,第二个在onfocuschange()中。

我建议您在对话框类中添加布尔变量,以指示对话框是否已经显示。

可以重写show()ondismiss()方法:

private boolean mIsShown = false;

@Override
public void show(FragmentManager manager, String tag) {    
    super.show(manager, tag);
    mIsShown = true;
}

@Override
public void onDismiss(DialogInterface dialog) {
    mIsShown = false;
    super.onDismiss(dialog);
}

public boolean isDialogShown(){
    return mIsShown;
}
DatePickerFragment mPickerFragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.cardviewinput);

    fListenerEditText = (ListenerEditText) findViewById(R.id.FEditText);

    fListenerEditText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(mPickerFragment == null || !mPickerFragment.isDialogShown()){
               mPickerFragment = new DatePickerFragment();
               mPickerFragment.show(getSupportFragmentManager(), "datePicker");
            }
        }
    });

    fListenerEditText.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus && (fListenerEditText.getText().length() == 0) && ((mPickerFragment == null || !mPickerFragment.isDialogShown()))) {
                mPickerFragment = new DatePickerFragment();
                mPickerFragment.show(getSupportFragmentManager(), "datePicker");
            }
        }
    });
}
 类似资料:
  • 我试图弄清楚如何在显示时选择一个选项,使用旧的javascript风格代码或其他语言,例如: 在angularjs中尝试这样做时,我最终得到了类似下面所示的东西。 这是代码: 如何才能正确地执行此操作?

  • 我的脚本如下: 我的html输入字段如下所示: 当我单击图像时,我正在获取输入字段的ui日历,请帮助我禁用日历中以前的日期,以便用户只能从今天开始选择开始日期。非常感谢。

  • 我有两个下拉列表,我想在它们被选中后使用它们。我想在选择的基础上弹出另一个框来显示信息。当我尝试使用if语句并按下ok按钮时,它只是继续到下一行。我从一个showMessage对话框开始,但我想在一些下拉选项中显示警告。它不起作用。我还需要能够循环返回主菜单,以便他们可以做出不同的选择。 我现在拥有的例子:

  • 问题内容: 有没有检查连续日期的功能。我在处理以下问题时遇到问题: 我的表有一个包含以下数据的列: 给定的开始日期为,结束日期为。我想要的结果是: 有人可以建议什么吗? 问题答案: 我认为这是 “连续日期分组岛” 问题的一种变体。可以使用以下方法完成: SQL小提琴 结果 这是SQL Server 2005版本: SQL小提琴

  • 问题内容: 我在postgres数据库中有一个时间戳字段。我想选择上个月内发生的所有日期。因此,类似于从表中选择 ,其中timestamp>(当前时间戳-1个月)。 问题答案:

  • 我想把日期的限制,以便用户不能选择更多的日期,例如,如果今天是1月1日,那么用户不应该能够选择超过7个日期,我的意思是他不能选择1月9日。我也希望他不要选择月份和年份。所以我限制他在一周内完成任务。 到目前为止,我所做的是显示日期选择器片段并在其中设置当前日期。我的主活动中的代码如下所示: 日期选择器片段类如下所示: 它将当前日期设置为最大日期,但我如何添加7天前,因为它是日期对象?请帮忙