Android时间选择器弹出问题

时间:2017-02-17 08:53:15

标签: java android popup datetimepicker

尝试创建一个简单的时间选择器来填充按钮,我在下面看到了这个代码,它似乎正在寻找 - 但在运行时崩溃。你们可以指出问题或提供更好的代码。提前谢谢。

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        />
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onButtonClicked"
        android:text="Set Time"
        android:layout_below="@id/tv"
        />
</RelativeLayout>

这是代码

package com.example.xxxx;

import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.app.Fragment;
import android.text.format.DateFormat;
import android.view.Gravity;
import android.widget.TextView;
import android.app.DialogFragment;
import android.app.Dialog;
import java.util.Calendar;
import android.widget.TimePicker;


/**
 * A simple {@link Fragment} subclass.
 */
public class MainActivity extends DialogFragment implements TimePickerDialog.OnTimeSetListener{

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState){
        //Use the current time as the default values for the time picker
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        //Create and return a new instance of TimePickerDialog
        /*
            public constructor.....
            TimePickerDialog(Context context, int theme,
             TimePickerDialog.OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView)

            The 'theme' parameter allow us to specify the theme of TimePickerDialog

            .......List of Themes.......
            THEME_DEVICE_DEFAULT_DARK
            THEME_DEVICE_DEFAULT_LIGHT
            THEME_HOLO_DARK
            THEME_HOLO_LIGHT
            THEME_TRADITIONAL

         */
        TimePickerDialog tpd = new TimePickerDialog(getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_DARK
                ,this, hour, minute, DateFormat.is24HourFormat(getActivity()));

        //You can set a simple text title for TimePickerDialog
        //tpd.setTitle("Title Of Time Picker Dialog");

        /*.........Set a custom title for picker........*/
        TextView tvTitle = new TextView(getActivity());
        tvTitle.setText("TimePickerDialog Title");
        tvTitle.setBackgroundColor(Color.parseColor("#EEE8AA"));
        tvTitle.setPadding(5, 3, 5, 3);
        tvTitle.setGravity(Gravity.CENTER_HORIZONTAL);
        tpd.setCustomTitle(tvTitle);
        /*.........End custom title section........*/

        return tpd;
    }

    //onTimeSet() callback method
    public void onTimeSet(TimePicker view, int hourOfDay, int minute){
        //Do something with the user chosen time
        //Get reference of host activity (XML Layout File) TextView widget
        TextView tv = (TextView) getActivity().findViewById(R.id.tv);
        //Set a message for user

        //Get the AM or PM for current time
        String aMpM = "AM";
        if(hourOfDay >11)
        {
            aMpM = "PM";
        }

        //Make the 24 hour time format to 12 hour time format
        int currentHour;
        if(hourOfDay>11)
        {
            currentHour = hourOfDay - 12;
        }
        else
        {
            currentHour = hourOfDay;
        }

        tv.setText("Your chosen time is...\n\n");
        //Display the user changed time on TextView
        tv.setText(tv.getText()+ String.valueOf(currentHour)
                + " : " + String.valueOf(minute) + " " + aMpM + "\n");

    }

错误日志

02-17 08:58:46.497: E/AndroidRuntime(21811): FATAL EXCEPTION: main
02-17 08:58:46.497: E/AndroidRuntime(21811): Process: com.example.xxxx, PID: 21811
02-17 08:58:46.497: E/AndroidRuntime(21811): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.xxxx/com.example.xxxx.MainActivity}: java.lang.ClassCastException: com.example.xxxx.MainActivity cannot be cast to android.app.Activity
02-17 08:58:46.497: E/AndroidRuntime(21811):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3093)
02-17 08:58:46.497: E/AndroidRuntime(21811):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
02-17 08:58:46.497: E/AndroidRuntime(21811):    at android.app.ActivityThread.access$1100(ActivityThread.java:221)
02-17 08:58:46.497: E/AndroidRuntime(21811):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
02-17 08:58:46.497: E/AndroidRuntime(21811):    at android.os.Handler.dispatchMessage(Handler.java:102)
02-17 08:58:46.497: E/AndroidRuntime(21811):    at android.os.Looper.loop(Looper.java:158)
02-17 08:58:46.497: E/AndroidRuntime(21811):    at android.app.ActivityThread.main(ActivityThread.java:7224)
02-17 08:58:46.497: E/AndroidRuntime(21811):    at java.lang.reflect.Method.invoke(Native Method)
02-17 08:58:46.497: E/AndroidRuntime(21811):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
02-17 08:58:46.497: E/AndroidRuntime(21811):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
02-17 08:58:46.497: E/AndroidRuntime(21811): Caused by: java.lang.ClassCastException: com.example.xxxx.MainActivity cannot be cast to android.app.Activity
02-17 08:58:46.497: E/AndroidRuntime(21811):    at android.app.Instrumentation.newActivity(Instrumentation.java:1095)
02-17 08:58:46.497: E/AndroidRuntime(21811):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3083)
02-17 08:58:46.497: E/AndroidRuntime(21811):    ... 9 more

1 个答案:

答案 0 :(得分:1)

为此使用自定义布局。你必须在下面按下time_picker_dialod.xml

按钮
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/accentcolor"
    android:padding="8dp">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/date_time_set">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="10dp"
            android:orientation="vertical">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="Select Time"
                android:textSize="14sp"
                android:textStyle="bold" />

            <TimePicker
                android:id="@+id/time_picker"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>
    </ScrollView>

    <Button
        android:id="@+id/date_time_set"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="Set Time" />

</RelativeLayout>

现在您可以在对话框中使用此布局,如下所示

ProgressDialog progressDialog = new ProgressDialog(Add_ReminderActivity.this);
                progressDialog.setMessage("Please wait.");
                progressDialog.show();

                final View dialogView = View.inflate(Add_ReminderActivity.this, R.layout.time_picker_dialod, null);

                final AlertDialog alertDialog = new AlertDialog.Builder(Add_ReminderActivity.this).create();
                alertDialog.setView(dialogView);

                final TimePicker timePicker = (TimePicker) dialogView.findViewById(R.id.time_picker);

                if (Build.VERSION.SDK_INT >= 23) {
                    timePicker.setHour(00);
                    timePicker.setMinute(00);
                } else {
                    timePicker.setCurrentHour(00);
                    timePicker.setCurrentMinute(00);
                }

                dialogView.findViewById(R.id.date_time_set).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        if (Build.VERSION.SDK_INT >= 23) {
                            Selected_From_Time = Uri.encode(DigitPad(timePicker.getHour()) + ":" + DigitPad(timePicker.getMinute()) + ":" + "00");
                        } else {
                            Selected_From_Time = Uri.encode(DigitPad(timePicker.getCurrentHour()) + ":" + DigitPad(timePicker.getCurrentMinute()) + ":" + "00");
                        }

                        alertDialog.dismiss();
                    }
                });

                alertDialog.show();
                if (alertDialog.isShowing()) {
                    progressDialog.dismiss();
                }

DigitPad功能:

public String DigitPad(int myNumber) {
        String mNumber = String.valueOf(myNumber);
        return (mNumber.toString().length() < 2) ? "0" + mNumber : mNumber;
    }

希望这可以帮助你