DatePicker和TimePicker组合后的Dialog

记录一下刚刚实现的一个组合的选择时间和日期的Dialog,可以根据自己的实际需要把日期中的 年、月、日的spinner隐藏,在类中已经提供了此方法,但是实际Demo并没有使用。

先展示完整的图片:
DatePicker和TimePicker组合后的Dialog_第1张图片
DatePicker和TimePicker组合后的Dialog_第2张图片
以下是:这是Activity代码

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


public class TimeDateActivity extends Activity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_time_date);
        Button btnDialog = (Button) findViewById(R.id.btn_dialog);
        btnDialog.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        new DateDialog(TimeDateActivity.this, new DateDialog.DateCallBack() {
            @Override
            public void onClick(String date) {
                Toast.makeText(TimeDateActivity.this, date + "", Toast.LENGTH_LONG).show();
            }
        });
    }
}

下面是主布局部分代码:

  <Button
        android:text="弹出Dialog"
        android:id="@+id/btn_dialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

下面是Dialog的布局代码:

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

    <DatePicker  android:layout_width="match_parent" android:id="@+id/date" android:calendarViewShown="false" android:layout_height="wrap_content" />

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

接下来才是最重要的Dialog的代码:

package cn.edu.jxufe.demo01;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TimePicker;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Calendar;


/** * 日期时间选择组合控件 * 使用方法: * 在Activity中:点击按钮,调用下面的函数 * new DateDialog(this, new DateDialog.DateCallBack() { * * @ Override * public void onChanged(String date) { * Toast.makeText(TimeDateActivity.this, date + "", Toast.LENGTH_LONG).show(); * } * }); */
public class DateDialog implements DatePicker.OnDateChangedListener, TimePicker.OnTimeChangedListener {
    private String dateTime;
    private Context context;
    private DateCallBack listener;
    private DatePicker datePicker;
    private TimePicker timePicker;
    private View view;

    /** * 日期时间弹出选择框构造函数 * * @param context:获取组件的上下文 */
    public DateDialog(Context context, DateCallBack listener) {
        this.context = context;
        this.listener = listener;
        //初始化视图中的控件
        initPicker();
        //初始化Dialog
        initDialog();

    }

    /** * 初始化Picker和主视图 */
    private void initPicker() {
        view = LayoutInflater.from(context).inflate(R.layout.dialog_time_date_view, null);

        datePicker = (DatePicker) view.findViewById(R.id.date);
        timePicker = (TimePicker) view.findViewById(R.id.time);

        Calendar calendar = Calendar.getInstance();
        //隐藏年份 spinner 控件,也可以隐藏月份或日份
        //hidYear(datePicker);
        datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH), this);
        timePicker.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY));
        timePicker.setCurrentMinute(calendar.get(Calendar.MINUTE));
        timePicker.setIs24HourView(true);
        timePicker.setOnTimeChangedListener(this);
    }

    /** * 弹出日期时间选择框方法 */
    public void initDialog() {
        //初始化Dialog
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setIcon(R.drawable.ic_launcher);
        builder.setView(view);
        builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                listener.onClick(dateTime);
            }
        });
        builder.setNegativeButton("取消", null).create();
        builder.show();
        //刷新数据
        onDateChanged(null, 0, 0, 0);
    }

    /** * 隐藏 选择 年份 的spinner * mYearSpinner:年份spinner * mMonthSpinner:月份spinner * mDaySpinner:日份spinner */
    private void hidYear(DatePicker mDatePicker) {
        Field[] datePickerFields = mDatePicker.getClass().getDeclaredFields();
        for (Field datePickerField : datePickerFields) {

            if ("mYearSpinner".equals(datePickerField.getName())) {
                datePickerField.setAccessible(true);
                Object dayPicker = new Object();
                try {
                    dayPicker = datePickerField.get(mDatePicker);
                } catch (IllegalAccessException | IllegalArgumentException e) {
                    e.printStackTrace();
                }
                ((View) dayPicker).setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
        onDateChanged(null, 0, 0, 0);
    }

    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
        Calendar calendar = Calendar.getInstance();

        calendar.set(datePicker.getYear(), datePicker.getMonth(),
                datePicker.getDayOfMonth(), timePicker.getCurrentHour(),
                timePicker.getCurrentMinute());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        dateTime = sdf.format(calendar.getTime());
    }

    //采用接口回调的方式 获取点击dialog的'设置'之后的数据
    public interface DateCallBack {
        public void onClick(String date);
    }
}

以上就是全部,本人还只是个学了半年Android的小白,如果这个Demo有什么问题,请大家在下面留言,我定当及时改正,谢谢。

你可能感兴趣的:(android)