DatePickerDialog

时间:2012-03-25 15:46:55

标签: android datepickerdialog

我正试图在Android documentation

中找到简单的DatePickerDialog工作代码。


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

import java.util.Calendar;

public class DatePickerDialogExample extends Activity {
    private TextView mDateDisplay;
    private Button mPickDate;
    private int mYear;
    private int mMonth;
    private int mDay;

    static final int DATE_DIALOG_ID = 0;

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

        mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
        mPickDate = (Button) findViewById(R.id.pickDate);

        mPickDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });

        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);

        updateDisplay();
    }

    private void updateDisplay() {
        mDateDisplay.setText(
                new StringBuilder()
                        .append(mMonth + 1).append("-")
                        .append(mDay).append("-")
                        .append(mYear).append(" "));
    }

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

                public void onDateSet(DatePicker view, int year,
                                      int monthOfYear, int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    updateDisplay();
                }
            };

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DATE_DIALOG_ID:
                return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
                        mDay);
        }
        return null;
    }

}

但是我遇到了奇怪的错误

02-09 15:37:26.491: ERROR/AndroidRuntime(10174): FATAL EXCEPTION: main
        android.view.InflateException: Binary XML file line #48: Error inflating class android.widget.ImageView
        at android.view.LayoutInflater.createView(LayoutInflater.java:518)
        at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:568)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:623)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:626)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:626)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:408)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
        at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:207)
        at com.android.internal.app.AlertController.installContent(AlertController.java:205)
        at android.app.AlertDialog.onCreate(AlertDialog.java:251)
        at android.app.Dialog.dispatchOnCreate(Dialog.java:307)
        at android.app.Activity.createDialog(Activity.java:886)
        at android.app.Activity.showDialog(Activity.java:2557)
        at android.app.Activity.showDialog(Activity.java:2524)
        at uk.co.peterscrorner.DatePickerDialogExample$1.onClick(DatePickerDialogExample.java:33)
        at android.view.View.performClick(View.java:2485)
        at android.view.View$PerformClick.run(View.java:9080)
        at android.os.Handler.handleCallback(Handler.java:587)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:123)
        at android.app.ActivityThread.main(ActivityThread.java:3683)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:507)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
        at dalvik.system.NativeStart.main(Native Method)
        Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.constructNative(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:415)
        at android.view.LayoutInflater.createView(LayoutInflater.java:505)
        ... 27 more
        Caused by: android.content.res.Resources$NotFoundException: File res/drawable-mdpi/ic_dialog_info.png from drawable resource ID #0x108009b
        at android.content.res.Resources.loadDrawable(Resources.java:1714)
        at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
        at android.widget.ImageView.(ImageView.java:118)
        at android.widget.ImageView.(ImageView.java:108)
        ... 30 more
        Caused by: java.io.FileNotFoundException: res/drawable-mdpi/ic_dialog_info.png
        at android.content.res.AssetManager.openNonAssetNative(Native Method)
        at android.content.res.AssetManager.openNonAsset(AssetManager.java:406)
        at android.content.res.Resources.loadDrawable(Resources.java:1706)
        ... 33 more

6 个答案:

答案 0 :(得分:9)

在XML中添加TextView和Button

<TextView
    android:id="@+id/searchText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView" />

<Button
    android:id="@+id/search"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Search" />

在java文件中添加以下代码

public class DatePickerDialogExample extends Activity {

    TextView txtDate;
    private int mYear, mMonth, mDay, mHour, mMinute;

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


        txtDate = (TextView) findViewById(R.id.searchText);
        Button search = (Button) findViewById(R.id.search);
        search.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // Process to get Current Date
            final Calendar c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);

            // Launch Date Picker Dialog
            DatePickerDialog dpd = new DatePickerDialog(PrayTimeActivity.this,
                    new DatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet(DatePicker view, int year,
                                int monthOfYear, int dayOfMonth) {
                            // Display Selected date in textbox
                            txtDate.setText(dayOfMonth + "-"
                                    + (monthOfYear + 1) + "-" + year);

                        }
                    }, mYear, mMonth, mDay);
                dpd.show();
            }
        });


    }

}

答案 1 :(得分:0)

请你试试这个:DatePickerDialog

答案 2 :(得分:0)

PS:在setOnClickListener解决问题之前启动日,月和年变量。

OR

试试这个简单的套餐:

public class DialogSelectDate extends AppCompatActivity {

    /**
     * Desenvolvido por Eduardo Ferreira
     * Simple DialogBox to DatePicker
     * @param _context
     * @param fromDateEtxt
     * @param dateFormatter
     */
    static void DialogDate(Context _context , final EditText fromDateEtxt , final SimpleDateFormat dateFormatter) {
        fromDateEtxt.setInputType(InputType.TYPE_NULL);
        fromDateEtxt.requestFocus();

        Calendar newCalendar = Calendar.getInstance();
        final DatePickerDialog fromDatePickerDialog = new DatePickerDialog(_context, new DatePickerDialog.OnDateSetListener() {
            public void onDateSet(DatePicker view , int year , int monthOfYear , int dayOfMonth) {
                Calendar newDate = Calendar.getInstance();
                newDate.set(year , monthOfYear , dayOfMonth);
                fromDateEtxt.setText(dateFormatter.format(newDate.getTime()));
            }
        } , newCalendar.get(Calendar.YEAR) , newCalendar.get(Calendar.MONTH) , newCalendar.get(Calendar.DAY_OF_MONTH));
        fromDateEtxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fromDatePickerDialog.show();
            }
        });
    }
}

调用你的项目

        EditText ed_edittext = findViewById(R.id.edittext);
        SimpleDateFormat dateFormatter = new SimpleDateFormat(`dd-MM-yyyy`, locale.US);

        DialogSelectDate.DialogDate(this, ed_edittext, dateFormatter );

答案 3 :(得分:0)

Date Picker Dialog in Android Kotlin: - In This Dialog you can set min and max Date: -  

val dp = fromDatePickerDialog.datePicker dp.minDate = System.currentTimeMillis()

fun getDateDialog(textView: TextView, sActivity: Activity?): DatePickerDialog? {
            val fromDatePickerDialog: DatePickerDialog
            val newCalendar: Calendar = Calendar.getInstance()
            val dateFormatter = SimpleDateFormat("MMM/dd/yyyy", Locale.US)
            fromDatePickerDialog = DatePickerDialog(
                sActivity!!,
                { view, year, monthOfYear, dayOfMonth ->
                    val newDate: Calendar = Calendar.getInstance()
                    newDate.set(year, monthOfYear, dayOfMonth)
                    textView.setText(dateFormatter.format(newDate.getTime()))
                },
                newCalendar.get(Calendar.YEAR),
                newCalendar.get(Calendar.MONTH),
                newCalendar.get(Calendar.DAY_OF_MONTH)
            )
            val dp = fromDatePickerDialog.datePicker
            dp.minDate = System.currentTimeMillis()
            fromDatePickerDialog.show()
            return fromDatePickerDialog
        }

答案 4 :(得分:0)

试试这个,你可以设置最大日期最小日期并格式化日期

fun showDatePicker(context: Context, maximumDate: Long? = null, minimumDate: Long? = null, dateFormat: String = "dd/MM/yyyy",callBack: (String) -> Unit) {
    val c = Calendar.getInstance()
    val year = c.get(Calendar.YEAR)
    val month = c.get(Calendar.MONTH)
    val day = c.get(Calendar.DAY_OF_MONTH)

    val dateSetListener = DatePickerDialog.OnDateSetListener { _, _year, monthOfYear, dayOfMonth ->
        c.set(Calendar.YEAR, _year)
        c.set(Calendar.MONTH, monthOfYear)
        c.set(Calendar.DAY_OF_MONTH, dayOfMonth)

        val sdf = SimpleDateFormat(dateFormat, Locale.US)
        callBack(sdf.format(c.time))
    }
    val datePickerDialog = DatePickerDialog(context, dateSetListener, year, month, day)

    if (minimumDate != null) {
        datePickerDialog.datePicker.minDate = minimumDate
    }
    if (maximumDate != null) {
        datePickerDialog.datePicker.maxDate = maximumDate
    }
    datePickerDialog.show()


}

答案 5 :(得分:-1)

演示如何使用DatePickerDialog的简单示例:

Calendar c = Calendar.getInstance();

new DatePickerDialog(this, new OnDateSetListener() {

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        // Do something here
    }
}, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show();