2013-12-23 3 views
0

У меня есть 2 выбора даты в одном действии. То, что я хочу сделать, - это когда пользователь пытается выбрать дату со второго выбора даты, тогда эта дата должна быть больше, чем дата даты выбора даты, иначе она должна отображать диалоговое окно предупреждения.Как ограничить пользователя установкой даты на основе другой даты с даты выбора в android

Так что ниже приведен мой код.

public class Assignment_Create extends Activity implements OnClickListener { 

DataManipulator dataManipulator; 
static final int DIALOG_ID = 1; 

ImageView imageViewDateAssign, imageViewDueDate, imageViewSubmit; 
TextView textViewDtAssign, textViewDueDt; 
EditText editTextTitle, editTextDesc; 

static final int DATE_DIALOG_ID = 0; 
int cDay, cMonth, cYear; 

private TextView activeDateDisplay; 
private Calendar activeDate; 

// Update database 
String updateId; 
public boolean isEdit; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    this.requestWindowFeature(Window.FEATURE_NO_TITLE); 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.assignment_create); 

    imageViewDateAssign = (ImageView) findViewById(R.id.dateassign); 
    imageViewDueDate = (ImageView) findViewById(R.id.duedate); 
    imageViewSubmit = (ImageView) findViewById(R.id.submit); 

    textViewDtAssign = (TextView) findViewById(R.id.textViewDateAssign); 
    textViewDueDt = (TextView) findViewById(R.id.textViewDueDate); 

    editTextTitle = (EditText) findViewById(R.id.title); 
    editTextDesc = (EditText) findViewById(R.id.description); 

    isEdit = getIntent().getExtras().getBoolean("isEdit"); 
    updateId = getIntent().getExtras().getString("idNo"); 

    if (isEdit) { 
     editTextTitle.setText(getIntent().getExtras().getString(
       "AsmntTitle")); 
     editTextDesc 
       .setText(getIntent().getExtras().getString("AsmntDesc")); 
    } 

    Code.AssignDate = Calendar.getInstance(); 
    Code.DueDate = Calendar.getInstance(); 

    imageViewDateAssign.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View arg0) { 
      showDateDialog(textViewDtAssign, Code.AssignDate); 
     } 
    }); 

    imageViewDueDate.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View arg0) { 
      showDateDialog(textViewDueDt, Code.DueDate); 
     } 
    }); 

    imageViewSubmit.setOnClickListener(this); 

    updateDisplay(textViewDtAssign, Code.AssignDate); 
    updateDisplay(textViewDueDt, Code.DueDate); 
} 

public void onClick(View v) { 
    switch (v.getId()) { 
    case R.id.submit: 

     Code.title = editTextTitle.getText().toString().trim(); 
     Code.description = editTextDesc.getText().toString().trim(); 
     Code.diff = Code.DueDate.getTimeInMillis() 
       - Code.AssignDate.getTimeInMillis(); 
     Code.days = Code.diff/(24 * 60 * 60 * 1000); 
     Code.strDays = String.valueOf(Code.days); 

     Date assignDate = new Date(Code.AssignDate.getTimeInMillis()); 
     Date dueDate = new Date(Code.DueDate.getTimeInMillis()); 

     if (dueDate.before(assignDate) || dueDate.equals(assignDate)) { 
      AlertDialog.Builder myDialogBattery = new AlertDialog.Builder(
        Assignment_Create.this); 
      myDialogBattery.setTitle("How to use Less Battery"); 
      myDialogBattery.setMessage("hahahahahaha"); 
      myDialogBattery.setPositiveButton("OK", 
        new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface arg0, int arg1) { 
         } 
        }); 
      myDialogBattery.show(); 
     } 

     if (isEdit) { 
      this.dataManipulator = new DataManipulator(this); 
      this.dataManipulator.update(updateId); 
      this.dataManipulator.close(); 
     } else { 
      this.dataManipulator = new DataManipulator(this); 
      this.dataManipulator.insert(Code.title, Code.description, 
        Code.strDays); 
      this.dataManipulator.close(); 
     } 

     Toast.makeText(getApplicationContext(), 
       "Details are saved successfully", Toast.LENGTH_LONG).show(); 
     Toast.makeText(getApplicationContext(), 
       "Assignment Created Succesfully", Toast.LENGTH_LONG).show(); 
     Assignment_Create.this.finish(); 
     break; 
    } 
} 

private void updateDisplay(TextView dateDisplay, Calendar date) { 
    dateDisplay.setText(new StringBuilder() 
      // Month is 0 based so add 1 
      .append(date.get(Calendar.MONTH) + 1).append("-") 
      .append(date.get(Calendar.DAY_OF_MONTH)).append("-") 
      .append(date.get(Calendar.YEAR)).append(" ")); 
} 

@SuppressWarnings("deprecation") 
public void showDateDialog(TextView dateDisplay, Calendar date) { 
    activeDateDisplay = dateDisplay; 
    activeDate = date; 
    showDialog(DATE_DIALOG_ID); 
} 

private OnDateSetListener dateSetListener = new OnDateSetListener() { 
    @Override 
    public void onDateSet(DatePicker view, int year, int monthOfYear, 
      int dayOfMonth) { 
     activeDate.set(Calendar.YEAR, year); 
     activeDate.set(Calendar.MONTH, monthOfYear); 
     activeDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); 
     updateDisplay(activeDateDisplay, activeDate); 

     unregisterDateDisplay(); 
    } 
}; 

private void unregisterDateDisplay() { 
    activeDateDisplay = null; 
    activeDate = null; 
} 

@Override 
protected Dialog onCreateDialog(int id) { 
    switch (id) { 
    case DATE_DIALOG_ID: 
     return new DatePickerDialog(this, dateSetListener, 
       activeDate.get(Calendar.YEAR), 
       activeDate.get(Calendar.MONTH), 
       activeDate.get(Calendar.DAY_OF_MONTH)); 
    } 
    return null; 
} 

@SuppressWarnings("deprecation") 
@Override 
protected void onPrepareDialog(int id, Dialog dialog) { 
    super.onPrepareDialog(id, dialog); 
    switch (id) { 
    case DATE_DIALOG_ID: 
     ((DatePickerDialog) dialog).updateDate(
       activeDate.get(Calendar.YEAR), 
       activeDate.get(Calendar.MONTH), 
       activeDate.get(Calendar.DAY_OF_MONTH)); 
     break; 
    } 
} 
} 

Я попытался с помощью следующей ссылке, но не получить решение, как я хочу

how to not allow user select past date in datepicker?

Setting upper and lower date limits to date picker dialog

How to set min-max age limit with datepicker android

Date Picker with max and minimum date in onDateChanged() in Android 1.5?

поэтому я устанавливаю дату, теперь, когда пользователь нажимает кнопку отправки, и если дата выбора даты меньше, чем дата выбора, тогда появляется диалоговое окно предупреждения.

Так что я делаю не так, может кто-нибудь мне помочь , Заранее спасибо.

ответ

1

Просто сравните getTimeInMillis Календаря

Calendar mCalendarFirst = Calendar.getInstance(); 
mSelectedCalendar.set(Calendar.YEAR, your_year_from_frist_datepicker); 
mSelectedCalendar.set(Calendar.MONTH, your_month_from_frist_datepicker); 
mSelectedCalendar.set(Calendar.DAY_OF_MONTH, your_day_from_frist_datepicker); 

Calendar mCalendarSecond = Calendar.getInstance(); 
mSelectedCalendar.set(Calendar.YEAR, your_year_from_second_datepicker); 
mSelectedCalendar.set(Calendar.MONTH, your_month_from_seconf_datepicker); 
mSelectedCalendar.set(Calendar.DAY_OF_MONTH, your_day_from_second_datepicker); 

if(mCalendarSecond.getTimeInMillis() <= mCalendarFirst.getTimeInMillis()) 
{ 
     //Your second date is less than first date 
     //Show your dialog here. 
} 

Update:

Для вашей ситуации использование ниже:

if(Code.DueDate.getTimeInMillis() <= Code.AssignDate.getTimeInMillis()) 
{ 
     //Your second date is less than first date 
     //Show your dialog here. 
} 

Try код ниже:

public void onClick(View v) { 
     switch (v.getId()) { 
     case R.id.submit: 

      Code.title = editTextTitle.getText().toString().trim(); 
      Code.description = editTextDesc.getText().toString().trim(); 

      Code.diff = Code.DueDate.getTimeInMillis() 
        - Code.AssignDate.getTimeInMillis(); 
      Code.days = Code.diff/(24 * 60 * 60 * 1000); 
      Code.strDays = String.valueOf(Code.days); 

      Date assignDate = new Date(Code.AssignDate.getTimeInMillis()); 
      Date dueDate = new Date(Code.DueDate.getTimeInMillis()); 

      if (Code.DueDate.getTimeInMillis() <= Code.AssignDate.getTimeInMillis()){ 
       AlertDialog.Builder myDialogBattery = new AlertDialog.Builder(
         Assignment_Create.this); 
       myDialogBattery.setTitle("How to use Less Battery"); 
       myDialogBattery.setMessage("hahahahahaha"); 
       myDialogBattery.setPositiveButton("OK", 
         new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface arg0, int arg1) { 
          } 
         }); 
       myDialogBattery.show(); 
      }else 
      { 
       if (isEdit) { 
        this.dataManipulator = new DataManipulator(this); 
        this.dataManipulator.update(updateId); 
        this.dataManipulator.close(); 
       } else { 
        this.dataManipulator = new DataManipulator(this); 
        this.dataManipulator.insert(Code.title, Code.description, 
          Code.strDays); 
        this.dataManipulator.close(); 
       } 

       Toast.makeText(getApplicationContext(), 
         "Details are saved successfully", Toast.LENGTH_LONG).show(); 
       Toast.makeText(getApplicationContext(), 
         "Assignment Created Succesfully", Toast.LENGTH_LONG).show(); 
       Assignment_Create.this.finish(); 
      } 
      break; 
     } 
    } 
+0

Смотрите мой отредактированный вопрос выше, я поставил активность, как это, то как я могу проверить это условие с моим кодом. – InnocentKiller

+0

@InnocentKiller проверить мой отредактированный ответ –

+0

Я тоже пробовал это, но это не работает, а не в диалоговом окне alert, он заканчивает мою деятельность и shwing -2 или -1 дней в списке-списке ... – InnocentKiller

0

попробуйте следующий код. Здесь firstDate и secondDate являются объектом Дата

if (firstDate.after(secondDate)) { OR //secondDate.before(firstDate) 

    //display alert here 

} else { 

} 
+0

Я тоже пробовал это, но он не работает ... – InnocentKiller

+0

В чем проблема, с которой вы столкнулись? –

+0

не отображается диалоговое окно с предупреждением. – InnocentKiller

Смежные вопросы