how to popup datepicker when click on edittext in

2019-07-17 07:19发布

I want to show date picker popup window. I have found some examples but I am not getting it properly. I have one edit text and I click on edit text the date picker dialog should pop up and after setting the date, the date should show in edit text in dd/mm/yyyy format in fragments. PLease provide me sample code or good links.

6条回答
老娘就宠你
2楼-- · 2019-07-17 07:54

Solution:

Make your EditText clickable and focusable false like,

<EditText
    android:id="@+id/etDOB"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="false"
    android:cursorVisible="false"
    android:focusable="false"
    android:hint="Select" />

Then in your Fragment Class, put below code,

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.layout_xxx, container, false);

    EditText etDOB=view.findViewById(R.id.etDOB);
    etDOB.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openDatePickerDialog(v);
        }
    });    
}

public void openDatePickerDialog(final View v) {
    // Get Current Date
    DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(),
            (view, year, monthOfYear, dayOfMonth) -> {
                String selectedDate = dayOfMonth + "/" + (monthOfYear + 1) + "/" + year; 
                switch (v.getId()) {
                    case R.id.etDOB:
                        ((EditText)v).setText(selectedDate);
                        break;                         
                }
            }, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));


    datePickerDialog.getDatePicker().setMaxDate(cal.getTimeInMillis());        
    datePickerDialog.show();
}
查看更多
▲ chillily
3楼-- · 2019-07-17 07:56
    Edittext edittext= findViewById(R.id.edittext);

private void getDate() {

    edtitext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Calendar mcurrentDate = Calendar.getInstance();

             mDay   = mcurrentDate.get(Calendar.DAY_OF_MONTH);
             mMonth = mcurrentDate.get(Calendar.MONTH);
             mYear  = mcurrentDate.get(Calendar.YEAR);
            DatePickerDialog datePickerDialog = new DatePickerDialog(AddDetails.this, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                    month = month + 1;
                    date = dayOfMonth + ":" + month + ":" + year;
                    edittext.setText(date);
                }
            }, mYear, mMonth, mDay);
            datePickerDialog.show();

        }
    });

}
查看更多
劳资没心,怎么记你
4楼-- · 2019-07-17 08:04

Step 1. Disable your edit text

'enabled=false'

Step 2. Set onClickListener on your Edit Text

Step 3. onClick of your EditText, call the function to open the Date picker Dialogue.

and onDateSelected, the overridden function will return date, you can extract the date, month and year from there and set that text as string in your Edit text.

Let me know if you need help with the code.

查看更多
疯言疯语
5楼-- · 2019-07-17 08:04

I have develop an easy way out. It is one time investment work

Copy the following class into your project...

public class DatePickerHelper {

    /********************************************DatePickerRelatedWork*****************************/
    public static void showDatePicker(Activity activity, OnDateSelectedListener listener, boolean shouldUsePreviousDate) {
        Calendar currentDate = Calendar.getInstance();
        int currentYear = currentDate.get(Calendar.YEAR);
        int currentMonth = currentDate.get(Calendar.MONTH);
        int currentDay = currentDate.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog datePicker = new DatePickerDialog(activity, new MyDateSetListener(listener), currentYear, currentMonth, currentDay);
        datePicker.setTitle("Select date");
        if (shouldUsePreviousDate){
            datePicker.getDatePicker().setMinDate(-1893475799000L);
        }else {
            datePicker.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
        }
        datePicker.show();
    }

    public static class MyDateSetListener implements DatePickerDialog.OnDateSetListener {

        private OnDateSelectedListener listener;

        public MyDateSetListener(OnDateSelectedListener listener) {

            this.listener = listener;
        }

        @Override
        public void onDateSet(DatePicker datepicker, int selectedYear, int selectedMonth, int selectedDay) {
            String selectedDateString = null;
            selectedMonth = selectedMonth + 1;
            if (selectedDay >= 0 && selectedDay < 10 && selectedMonth >= 0 && selectedMonth < 10) {
                selectedDateString = "0" + selectedDay + "-" + "0" + selectedMonth + "-" + selectedYear;
            } else if (selectedDay >= 0 && selectedDay < 10) {
                selectedDateString = "0" + selectedDay + "-" + selectedMonth + "-" + selectedYear;
            } else if (selectedMonth >= 0 && selectedMonth < 10) {
                selectedDateString = selectedDay + "-" + "0" + selectedMonth + "-" + selectedYear;
            } else {
                selectedDateString = selectedDay + "-" + selectedMonth + "-" + selectedYear;
            }
            listener.onDateSelected(selectedDateString);
        }
    }

    public interface OnDateSelectedListener {
        void onDateSelected(String selectedDateString);
    }
}

Then copy the below method into your fragment...

 private void showDatePickerDialog(){
        DatePickerHelper.showDatePicker(AddCashbookActivity.this, new DateTimePickerWork.OnDateSelectedListener() {
            @Override
            public void onDateSelected(String selectedDateString) {
                editText.setText(selectedDateString);
            }
        },true);
    }

Then call the above method from your EditText listener (both

OnFocusChangeListener

and

OnClickListener

)

Below is an example...

editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean hasFocus) {
            if (hasFocus){
                showDatePickerDialog();
            }
        }
    });
editText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showDatePickerDialog();
        }
    });

Change

editText

variable to your EditText variable name.

And you are done!


Understanding the code

The above class can be use multiple times in your project and you do not need to think about the inner work of the Helper class. The hard part has been done by the class and you only get a callback whenever a date is selected.

The

showDatePicker

method need 3 params.

  1. Activity object
  2. An OnDateSelectedListener object - like any other listener
  3. shouldUsePreviousDate - boolean param, which is responsible for if the date picker should allow user to select past dates or disabled it!

If you need to change the Date format, you may change the method

onDateSet

You may change 10-05-2018 to 10/05/2018 or anything else. Just read the body of the method and you will understand what to change.

Hope this will help you and many others.

EDIT

Add android:focusable="false" within the xml file of the EditText to allow for a single touch and then you can avoid using setOnFocusChangeListener in your java code.

查看更多
乱世女痞
6楼-- · 2019-07-17 08:10

Instead of using Edittext you can use custom layout with Textview inside it. And upon clicking that layout youy can open datepicker dialog and after selecting date from datepicker update Textview with that date

xml for layout

<RelativeLayout
        android:id="@+id/layout_custom"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="5dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:background="@drawable/background_rectangle">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tv_birth_date"
            android:textColor="@color/black"
            android:text="@string/date_format"
            android:layout_centerInParent="true"
            />

    </RelativeLayout>

Create a new file in drawable folder by name background_rectangle and paste the following code inside it

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<!-- This is the stroke you want to define -->
<stroke android:width="1dp"
    android:color="@color/black"/>

<!-- Optional, round your corners -->
<corners android:bottomLeftRadius="5dp"
    android:topLeftRadius="5dp"
    android:bottomRightRadius="5dp"
    android:topRightRadius="5dp" />

<!-- Optional, fill the rest of your background with a color or gradient, use transparent if you only want the border to be displayed-->
<gradient android:startColor="@android:color/transparent"
    android:endColor="@android:color/transparent"
    android:angle="90"/>

Now add the dependency in app level gradle file

implementation 'com.wdullaer:materialdatetimepicker:2.3.0'

Now inside activity implement the datapickerdialog.ondateselected method

class ABCActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener,OnClickListener{

DatePickerDialog datePickerDialog;
TextView textViewDate;
RelativeLayout customLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_abc);
    // findviewsby id 
      customLayout.setOnclickListener(this);


     }

     public void onClick(View v) {
        Calendar maxDate = Calendar.getInstance();
    maxDate.add(Calendar.DATE, 0);
    calendar = Calendar.getInstance();
    datePickerDialog = DatePickerDialog.newInstance(
            CalculatorAgeActivity.this,
            calendar.get(Calendar.YEAR), // Initial year selection
            calendar.get(Calendar.MONTH), // Initial month selection
            calendar.get(Calendar.DAY_OF_MONTH) // Inital day selection
    );

    datePickerDialog.setThemeDark(false);
    datePickerDialog.setAccentColor(Color.parseColor("#58a5f0"));
    datePickerDialog.setTitle("Select Date");
    datePickerDialog.show(getFragmentManager(), "DatePicker Dialog");
      }
     @Override
     public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {

    textViewDate.setText(Integer.toString(dayOfMonth) + "/" + Integer.toString(monthOfYear + 1) + "/" +
            Integer.toString(year));

}}
查看更多
Rolldiameter
7楼-- · 2019-07-17 08:12

Try this in the XML file:

    <EditText
   android:id="@+id/Birthday"
   custom:font="@string/font_avenir_book"
   android:clickable="true"
   android:editable="false"
   android:hint="@string/birthday"/>

Now in Java File:

 Calendar myCalendar = Calendar.getInstance();

EditText edittext= (EditText) findViewById(R.id.Birthday);
DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {
        // TODO Auto-generated method stub
        myCalendar.set(Calendar.YEAR, year);
        myCalendar.set(Calendar.MONTH, monthOfYear);
        myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        updateLabel();
    }

};

edittext.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        new DatePickerDialog(classname.this, date, myCalendar
                .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                myCalendar.get(Calendar.DAY_OF_MONTH)).show();
    }
});

Now add the method in the above activity.

 private void updateLabel() {
    String myFormat = "MM/dd/yy"; //In which you need put here
    SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

    edittext.setText(sdf.format(myCalendar.getTime()));
}

Add android:focusable="false" within the xml file of the EditText to allow for a single touch.

查看更多
登录 后发表回答