Search code examples
javaandroidandroid-studiobuttonandroid-studio-2.0

How do create a button that when pressed enters a calendar view, allowing the user to select a date?


How do code a button that when pressed enters a calendar view, allowing the user to select a date? (In both the Main Activity and xml)


Solution

  • There is no need to add library when you can do it yourself..... I used an editText here, you can do anything, an image, a button, textview

    MainActivity

    public class MainActivity extends AppCompatActivity {
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            final EditText editText = (EditText) findViewById(R.id.editText);
    
            editText.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    //To show current date in the datepicker
                    Calendar mcurrentDate=Calendar.getInstance();
                    int year = mcurrentDate.get(Calendar.YEAR);
                    int month = mcurrentDate.get(Calendar.MONTH);
                    int day = mcurrentDate.get(Calendar.DAY_OF_MONTH);
    
                    DatePickerDialog mDatePicker=new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {
                        public void onDateSet(DatePicker datepicker, int selectedYear, int selectedMonth, int selectedDay) {
                            // TODO Auto-generated method stub
                        /*      Your code   to get date and time    */
                            Log.e("Date Selected", "Month: " + selectedMonth + " Day: " + selectedDay + " Year: " + selectedYear);
                            editText.setText(selectedMonth + "/" + selectedDay + "/" + selectedYear);
                        }
                    },year, month, day);
                    mDatePicker.setTitle("Select date");
                    mDatePicker.show();
                }
            });
    
        }
    }
    

    XML

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.vzw.www.myapplication.MainActivity">
    
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText"/>
    
    </android.support.constraint.ConstraintLayout>