简体   繁体   English

单击片段中的edittext时如何弹出datepicker

[英]how to popup datepicker when click on edittext in fragment

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. 我有一个编辑文本,然后单击编辑文本,弹出日期选择器对话框,设置日期后,日期应以dd / mm / yyyy格式显示在编辑文本中。 PLease provide me sample code or good links. PLease为我提供示例代码或良好的链接。

Solution: 解:

Make your EditText clickable and focusable false like, 使您的EditText clickable and focusable false如,

<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, 然后在你的Fragment Class中,放下代码,

@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();
}

Try this in the XML file: 在XML文件中尝试:

    <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: 现在在Java文件中:

 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. 在EditText的xml文件中添加android:focusable="false"以允许单次触摸。

Step 1. Disable your edit text 步骤1.禁用编辑文本

'enabled=false'

Step 2. Set onClickListener on your Edit Text 步骤2.在编辑文本上设置onClickListener

Step 3. onClick of your EditText, call the function to open the Date picker Dialogue. 步骤3.单击您的EditText,调用该函数打开日期选择器对话框。

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. 和onDateSelected,重写的函数将返回日期,您可以从那里提取日期,月份和年份,并在编辑文本中将该文本设置为字符串。

Let me know if you need help with the code. 如果您需要有关代码的帮助,请告诉我们。

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 然后从EditText侦听器调用上面的方法(两者都是

OnFocusChangeListener OnFocusChangeListener

and

OnClickListener 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 EDITTEXT

variable to your EditText variable name. 变量到您的EditText变量名称。

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. 上面的类可以在你的项目中多次使用,你不需要考虑Helper类的内部工作。 The hard part has been done by the class and you only get a callback whenever a date is selected. 困难的部分已经由班级完成,只有在选择日期时才会收到回调。

The

showDatePicker showDatePicker

method need 3 params. 方法需要3个参数。

  1. Activity object 活动对象
  2. An OnDateSelectedListener object - like any other listener OnDateSelectedListener对象 - 与任何其他侦听器一样
  3. shouldUsePreviousDate - boolean param, which is responsible for if the date picker should allow user to select past dates or disabled it! shouldUsePreviousDate - 布尔参数,负责日期选择器是否应允许用户选择过去的日期或禁用它!

If you need to change the Date format, you may change the method 如果需要更改日期格式,可以更改方法

onDateSet onDateSet

You may change 10-05-2018 to 10/05/2018 or anything else. 您可以将10-05-2018更改为10/05/2018或其他任何内容。 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. 在EditText的xml文件中添加android:focusable="false"以允许单次触摸,然后您可以避免在Java代码中使用setOnFocusChangeListener

    Edittext edittext= findViewById(R.id.edittext);

private void getDate() { 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();

        }
    });

}

Instead of using Edittext you can use custom layout with Textview inside it. 您可以在其中使用带有Textview custom layout ,而不是使用Edittext And upon clicking that layout youy can open datepicker dialog and after selecting date from datepicker update Textview with that date 点击该布局后,您可以打开datepicker对话框,然后从Textview更新Textview datepicker日期

xml for layout xml用于布局

<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 在名为background_rectangle drawable文件夹中创建一个新文件,并在其中粘贴以下代码

<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 现在在app level gradle file添加依赖gradle file

implementation 'com.wdullaer:materialdatetimepicker:2.3.0'

Now inside activity implement the datapickerdialog.ondateselected method 现在,inside活动实现了datapickerdialog.ondateselected方法

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));

}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM