如何将以前选择的日期放入Android DatePickerDialog中?

时间:2015-09-19 03:32:37

标签: android android-edittext android-datepicker

我有一个简单的DatePickerFragment,它将今天的日期作为默认日期加载到向用户显示的DatePickerDialog中。然后,用户从DatePicker中选择一个日期,然后代码在EditText行上设置该日期。如果用户稍后再次单击EditText行来编辑他们选择的日期,我希望对话框显示所选日期,而不是今天的日期。

我在EditText行上使用了空白测试。如果为空,请在对话框中设置今天的日期。如果不为空,则从用户先前选择的EditText行设置Dialog中的现有日期。到目前为止,我已经尝试将Bundle中先前选择的日期从onDateSet传递回onCreateDialog。我得到一个致命异常:“片段已经处于活动状态”所以我的逻辑必须设置在与片段不正确的循环中。我在这里缺少什么?

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 个答案:

答案 0 :(得分:0)

当您的EditText为空并点击它时,您会显示两次对话框。 onClick()方法中的第一个和onFocusChange()中的第二个。

我建议你在Dialog类中添加一个boolean变量来指示对话框是否已经显示。

您可以覆盖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");
            }
        }
    });
}