user3416113
user3416113

Reputation: 61

android calendar view date picker

I want to set a DatePicker for user to choose a date, after user presses the EditText and chooses the date. I want it returned to EditText field. How may I do that?

Here is my code :

public class CompletedWorksActivity extends ActionBar {
    private TextView text_date;
    private DatePicker date_picker;
    private Button button;
    private EditText from;
    private EditText to;
    private int year;
    private int month;
    private int day;

    static final int DATE_DIALOG_ID = 100;



    @Override
    protected void onCreate(Bundle menuinstance){
        super.onCreate(menuinstance);
        setContentView(R.layout.completed_works);

        Intent intent = getIntent(); //gaunam
        User user = (User) intent.getSerializableExtra("user");
        from = (EditText) findViewById(R.id.datefrom);
        to = (EditText) findViewById(R.id.dateto);
    }


}

And xml needed for this code :

<LinearLayout
    android:id="@+id/searchFields"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/header"
    android:background="#ffffff"
    android:gravity="center_vertical"
    android:orientation="vertical"
    android:paddingLeft="13dp"
    android:paddingRight="13dp"
    android:paddingTop="22dp" >

    <!-- Object ID field -->

    <EditText
        android:id="@+id/datefrom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="22dp"
        android:background="@drawable/search_datefrom_field"
        android:inputType="date"
        android:minHeight="45dp"
        android:paddingLeft="45dp"
        android:paddingRight="5dp"
        android:singleLine="true"
        android:textColor="#404041" />

    <!-- Key field -->

    <EditText
        android:id="@+id/dateto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="22dp"
        android:background="@drawable/search_dateto_field"
        android:inputType="date"
        android:minHeight="45dp"
        android:paddingLeft="45dp"
        android:paddingRight="5dp"
        android:singleLine="true"
        android:textColor="#404041" />
</LinearLayout>

Is it better to start other activity for choosing a date with picker, or call date picker in this activity somehow?

Upvotes: 0

Views: 4906

Answers (4)

Fedir Tsapana
Fedir Tsapana

Reputation: 1352

Try to use this component: https://github.com/truefedex/android-date-picker

Like this:

if (calendarPopup == null) {
  calendarPopup = new PopupWindow(getContext());
  CalendarPickerView calendarView = new CalendarPickerView(getContext());
  CalendarNumbersView calendar = (CalendarNumbersView) calendarView.findViewById(com.phlox.datepick.R.id.calendar);
  calendar.setShowDayNames(false);
  calendarView.setListener(onDateSelectionListener);
  calendarPopup.setContentView(calendarView);
  calendarPopup.setWindowLayoutMode(
        MeasureSpec.makeMeasureSpec(llCalendar.getWidth(), MeasureSpec.EXACTLY),
        ViewGroup.LayoutParams.WRAP_CONTENT);
  calendarPopup.setHeight(1);
  calendarPopup.setWidth(llCalendar.getWidth());
  calendarPopup.setOutsideTouchable(true);
}
calendarPopup.showAsDropDown(llCalendar);

Upvotes: 1

Mike M.
Mike M.

Reputation: 39201

I think I misread your description, but I'll post this anyway.

I took your description to mean that you wanted a DatePickerDialog to open upon clicking on the from and to EditTexts. The following code will open the Dialog when either gets focus, then set the corresponding EditText's text to the date upon closing.

public class CompletedWorksActivity extends Activity
implements DatePickerDialog.OnDateSetListener
{ 
    private TextView text_date;
    private Button button; 
    private EditText from; 
    private EditText to;
    private int year;
    private int month;
    private int day;

    private DatePickerDialog date_picker;
    private boolean fromEdit;

    @Override
    protected void onCreate(Bundle menuinstance)
    {
        super.onCreate(menuinstance);
        setContentView(R.layout.main);

        Intent intent = getIntent(); //gaunam
        User user = (User) intent.getSerializableExtra("user");

        from = (EditText) findViewById(R.id.datefrom);
        to = (EditText) findViewById(R.id.dateto);
        Calendar cal = Calendar.getInstance();

        date_picker = new DatePickerDialog(this, this, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));        

        from.setOnFocusChangeListener(focusListener);

        to.setOnFocusChangeListener(focusListener);
    }

    @Override
    public void onDateSet(DatePicker dp, int y, int m, int d)
    {
        String cheapDate = (m + 1) + "/" + d + "/" + y;

        if (fromEdit)
        {
            from.setText(cheapDate);
        }
        else
        {
            to.setText(cheapDate);
        }
    }

    private View.OnFocusChangeListener focusListener = new View.OnFocusChangeListener()
    {
        @Override
        public void onFocusChange(View v, boolean hasFocus)
        {           
            if (hasFocus)
            {
                //   \/ Optional \/
                EditText edit = (EditText) v;
                int len = edit.getText().toString().length();

                if (len == 0)
                {
                //   /\ Optional /\

                    fromEdit = v.getId() == R.id.datefrom;
                    date_picker.show();

                //   \/ Optional \/                 
                }
                else
                {
                    edit.setSelection(0, len);
                }
                //   /\ Optional /\
            }
        }
    };
}

Edit:

I cleaned up the code a bit, and added additional functionality, if you care to use it. Now, when an EditText gets the focus, if it is empty, it will open the Dialog. If it is not empty, the Dialog will not show, but instead the EditText's text will be selected.

If you just want the Dialog to open, empty or not, just omit the code between the marked "Optional" comments.

Also, as of API Level 11 (HONEYCOMB), you can do the following:

date_picker.getDatePicker().setCalendarViewShown(true);

Upvotes: 2

Dilroop Singh
Dilroop Singh

Reputation: 544

import java.util.Calendar;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethod;
import android.view.inputmethod.InputMethodManager;
import android.widget.DatePicker;
import android.widget.EditText;

 public class MainActivity extends Activity implements OnClickListener{
 EditText from,to;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);  
      //  User user = (User) intent.getSerializableExtra("user");
        from = (EditText) findViewById(R.id.datefrom);
        to = (EditText) findViewById(R.id.dateto);
        from.setOnClickListener(this);
        to.setOnClickListener(this);
}

@Override
public void onClick(final View v) {
    // To Hide KeyBoard 
    InputMethodManager i = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    i.hideSoftInputFromWindow(((EditText)v).getWindowToken(), 0);


    Calendar c = Calendar.getInstance();
    final String seperator = " / "; 
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day =  c.get(Calendar.DAY_OF_MONTH);
    OnDateSetListener listener = new OnDateSetListener() 
    {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            // YYYY/MM/DD
            //change the format as per your requirement
            ((EditText)v).setText(year + seperator + monthOfYear + seperator + dayOfMonth);

        }
    };

    DatePickerDialog d = new DatePickerDialog(this,listener,year , month, day);
    d.show();

}


 }

This Code will set On Click Listener when ever user click on any of the edit text. DatePickerDialog box will open to select a date

Upvotes: 0

GvSharma
GvSharma

Reputation: 2670

call date picker in this activity only, that is how i prefer. it is some thing like this

  private void callDatePic() {
    new DatePickerDialog(AddFriendActivity.this, d, c.get(Calendar.YEAR),
            c.get(Calendar.MONTH),       c.get(Calendar.DAY_OF_MONTH)).show();
}
DatePickerDialog.OnDateSetListener d = new OnDateSetListener() {

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {
        date =  dayOfMonth + "-" + (monthOfYear + 1) + "-" + year;          
        c1.set(Calendar.MONTH, monthOfYear);
        c1.set(Calendar.YEAR, year);
        c1.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    dateFrom.setText(date);
    }

};
where c1 is Calender class object.

after this you will back to edit text where the edittext was filled with selected date. you can follow the same step for other edit text field also hope this helps

Upvotes: 1

Related Questions