按钮单击实现日期选择器并存储在编辑文本中

时间:2014-04-21 05:48:24

标签: android android-datepicker

我是android的新手并试图在android中实现date picker dialog

为此,我正在研究link - Date Picker - Developers Android

到目前为止,我已经了解但我的要求是当我点击button我需要获取日期选择器对话框时,当我设置日期选择器时,我需要在Edit Text中设置值。

根据链接,我们需要扩展DialogFragment并实施DatePickerDialog.OnDateSetListener ...

现在我的理解是遵循以下流程来实现这一目标:

  
      
  1. 使用仅日期选择器创建新XML。
  2.   
  3. 创建一个java文件并实现日期选择器代码。
  4.   
  5. 在父类按钮中,点击Intentdatepicker班级
  6.   
  7. 将值传递给父类Edit Text
  8.   

请指导我这个过程是否正确......如果没有,请以正确的方式指导我。

感谢您的时间

4 个答案:

答案 0 :(得分:2)

以下是完整的代码..

Button bt_setdate=(Button) findViewById(R.id.bt_setdate);
bt_setdate.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            showDialog(DATE_DIALOG_ID);
            // get the current date

        }
    });

和onCreate()

之外
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_DIALOG_ID:
        // set date picker as current date
          //Edit------------------------------------------//
            final Calendar c = Calendar.getInstance();
        Year  = c.get(Calendar.YEAR);
        Month = c.get(Calendar.MONTH);
        day   = c.get(Calendar.DAY_OF_MONTH);
       //Edit------------------------------------------//
        return new DatePickerDialog(this, datePickerListener, 
                year, month,day);
    }
    return null;
}

private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

    // when dialog box is closed, below method will be called.
    public void onDateSet(DatePicker view, int selectedYear,
            int selectedMonth, int selectedDay) {
        year = selectedYear;
        month = selectedMonth;
        day = selectedDay;
        String selmonth=cm.getMonth(month);

        bookingdate=String.valueOf(year)+"-"+String.valueOf(month)+"-"+String.valueOf(day);

    }
};

bookingdate包含所选日期。 并将其添加到您的布局

<DatePicker
    android:id="@+id/dpResult"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:visibility="gone"/>

答案 1 :(得分:1)

尝试以下代码: -

DatePickerDialog.OnDateSetListener                date;
Calendar                                          myCalendar;
dob_add_emp             = (TextView) findViewById(R.id.dob_add_emp);

myCalendar = Calendar.getInstance();

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

};

dob_add_emp.setOnClickListener(new OnClickListener()
{   
    @Override
    public void onClick(View v)
    {
        // TODO Auto-generated method stub
        if (dob_add_emp.getText().toString().equals(""))
        {
            new DatePickerDialog(AddEmployee.this, date, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar
                    .get(Calendar.DAY_OF_MONTH)).show();
        }
        else
        {
            String dob = dob_add_emp.getText().toString();
            String[] d = dob.split("-");

            new DatePickerDialog(AddEmployee.this, date, Integer.parseInt(d[0]), Integer.parseInt(d[1]) - 1, Integer.parseInt(d[2]))
                    .show();
        }
    }
});



@SuppressLint("SimpleDateFormat")

private void updateLabel()
{
    try


{
    // String myFormat = "MM/dd/yyyy"; // In which you need put here
    DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    Date current_date = new Date();
    Date session_date = sdf.parse(sdf.format(myCalendar.getTime()));
    int difference = current_date.compareTo(session_date);
    if (difference == 0)
    {
        dob_add_emp.setText(sdf.format(myCalendar.getTime()));
    }
    else if (difference < 0)
    {
        Toast.makeText(getBaseContext(), "Select date before current date", Toast.LENGTH_LONG).show();
    }
    else
    {
        dob_add_emp.setText(sdf.format(myCalendar.getTime()));
    }
}
catch (Exception e)
{
    // TODO: handle exception
    e.printStackTrace();
}
}

答案 2 :(得分:0)

您好请使用点击按钮的代码,您想要打开日期选择器对话框

 static final int DATE_DIALOG_ID = 999;
 private int year;
 private int month;
 private int day;

final Calendar c = Calendar.getInstance();

year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);

btnDate.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        showDialog(DATE_DIALOG_ID);
    }
 });

将以下方法添加到您的活动中

@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
    // set date picker as current date
    return new DatePickerDialog(this, datePickerListener, year, month,
            day);
}
return null;
}

public DatePickerDialog.OnDateSetListener datePickerListener =
                  new    DatePickerDialog.   OnDateSetListener(){

       // when dialog box is closed, below method will be called.
        public void onDateSet(DatePicker view, int selectedYear,
        int selectedMonth, int selectedDay) {
         year = selectedYear;
         month = selectedMonth;
         day = selectedDay;

         // set selected date into edittext
           txtDate.setText(new StringBuilder().append(month + 1).append("-")
            .append(day).append("-").append(year).append(" "));

        }
     };

您可以将日期格式化为您的要求..

答案 3 :(得分:0)

package com.androidexample.datepicker;

import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class DatePickerExample extends Activity {

    private TextView Output;
    private Button changeDate;

    private int year;
    private int month;
    private int day;

    static final int DATE_PICKER_ID = 1111; 

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Output = (TextView) findViewById(R.id.Output);
        changeDate = (Button) findViewById(R.id.changeDate);

        // Get current date by calender

        final Calendar c = Calendar.getInstance();
        year  = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day   = c.get(Calendar.DAY_OF_MONTH);

        // Show current date

        Output.setText(new StringBuilder()
                // Month is 0 based, just add 1
                .append(month + 1).append("-").append(day).append("-")
                .append(year).append(" "));

        // Button listener to show date picker dialog

        changeDate.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                // On button click show datepicker dialog 
                showDialog(DATE_PICKER_ID);

            }

        });
   }


    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_PICKER_ID:

            // open datepicker dialog. 
            // set date picker for current date 
            // add pickerListener listner to date picker
            return new DatePickerDialog(this, pickerListener, year, month,day);
        }
        return null;
    }

    private DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {

        // when dialog box is closed, below method will be called.
        @Override
        public void onDateSet(DatePicker view, int selectedYear,
                int selectedMonth, int selectedDay) {

            year  = selectedYear;
            month = selectedMonth;
            day   = selectedDay;

            // Show selected date 
            Output.setText(new StringBuilder().append(month + 1)
                    .append("-").append(day).append("-").append(year)
                    .append(" "));

           }
        };

}

main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/changeDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click To Change Date" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Current/Selected Date (M-D-YYYY): "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/Output"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />



</LinearLayout>
相关问题