关闭

安卓原生时间选择器,DatePicker和TimePicker并用,弹窗dialog

标签: android时间选择器时间弹窗DatePickerTimePicker
13950人阅读 评论(6) 收藏 举报
分类:

封装安卓原生时间选择器,DatePicker和TimePicker并用,弹窗dialog,用起来非常方便...

之前写的用起来麻烦,这回又优化了一下,有什么不对或是更简单的办法大家可评论....
看效果(看见不好看自己修修偷笑):
                  

public class TimePickerDialog {

    private Context mContext;
    private AlertDialog.Builder mAlertDialog;
    private int mHour, mMinute;
    private TimePickerDialogInterface timePickerDialogInterface;
    private TimePicker mTimePicker;
    private DatePicker mDatePicker;
    private int mTag = 0;
    private int mYear, mDay, mMonth;

    public TimePickerDialog(Context context) {
        super();
        mContext = context;
        timePickerDialogInterface = (TimePickerDialogInterface) context;
    }

    /**
     * 初始化DatePicker
     *
     * @return
     */
    private View initDatePicker() {
        View inflate = LayoutInflater.from(mContext).inflate(
                R.layout.datepicker_layout, null);
        mDatePicker = (DatePicker) inflate
                .findViewById(R.id.datePicker);
        resizePikcer(mDatePicker);
        return inflate;
    }

    /**
     * 初始化TimePicker
     *
     * @return
     */
    private View initTimePicker() {
        View inflate = LayoutInflater.from(mContext).inflate(
                R.layout.timepicker_layout, null);
        mTimePicker = (TimePicker) inflate
                .findViewById(R.id.timePicker);
        mTimePicker.setIs24HourView(true);
        resizePikcer(mTimePicker);
        return inflate;
    }

    private View initDateAndTimePicker() {
        View inflate = LayoutInflater.from(mContext).inflate(
                R.layout.dateandtimepicker_layout, null);
        mTimePicker = (TimePicker) inflate
                .findViewById(R.id.dateAndTimePicker_timePicker);
        mDatePicker = (DatePicker) inflate
                .findViewById(R.id.dateAndTimePicker_datePicker);
        mTimePicker.setIs24HourView(true);
        resizePikcer(mTimePicker);
        resizePikcer(mDatePicker);
        return inflate;
    }

    /**
     * 创建dialog
     *
     * @param view
     */
    private void initDialog(View view) {
        mAlertDialog.setPositiveButton("确定",
                new android.content.DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.dismiss();

                        if (mTag == 0) {
                            getTimePickerValue();
                        } else if (mTag == 1) {
                            getDatePickerValue();
                        } else if (mTag == 2) {
                            getDatePickerValue();
                            getTimePickerValue();
                        }
                        timePickerDialogInterface.positiveListener();

                    }
                });
        mAlertDialog.setNegativeButton("取消",
                new android.content.DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        timePickerDialogInterface.negativeListener();
                        dialog.dismiss();
                    }
                });
        mAlertDialog.setView(view);
    }

    /**
     * 显示时间选择器
     */
    public void showTimePickerDialog() {
        mTag=0;
        View view = initTimePicker();
        mAlertDialog = new AlertDialog.Builder(mContext);
        mAlertDialog.setTitle("选择时间");
        initDialog(view);
        mAlertDialog.show();
        
    }

    /**
     * 显示日期选择器
     */
    public void showDatePickerDialog() {
        mTag=1;
        View view = initDatePicker();
        mAlertDialog = new AlertDialog.Builder(mContext);
        mAlertDialog.setTitle("选择时间");
        initDialog(view);
        mAlertDialog.show();
    }
    /**
     * 显示日期选择器
     */
    public void showDateAndTimePickerDialog() {
        mTag=2;
        View view = initDateAndTimePicker();
        mAlertDialog = new AlertDialog.Builder(mContext);
        mAlertDialog.setTitle("选择时间");
        initDialog(view);
        mAlertDialog.show();
    }

    /*
    * 调整numberpicker大小
    */
    private void resizeNumberPicker(NumberPicker np) {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(120,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        params.setMargins(10, 0, 10, 0);
        np.setLayoutParams(params);
    }

    /**
     * 调整FrameLayout大小
     *
     * @param tp
     */
    private void resizePikcer(FrameLayout tp) {
        List<NumberPicker> npList = findNumberPicker(tp);
        for (NumberPicker np : npList) {
            resizeNumberPicker(np);
        }
    }

    /**
     * 得到viewGroup里面的numberpicker组件
     *
     * @param viewGroup
     * @return
     */
    private List<NumberPicker> findNumberPicker(ViewGroup viewGroup) {
        List<NumberPicker> npList = new ArrayList<NumberPicker>();
        View child = null;
        if (null != viewGroup) {
            for (int i = 0; i < viewGroup.getChildCount(); i++) {
                child = viewGroup.getChildAt(i);
                if (child instanceof NumberPicker) {
                    npList.add((NumberPicker) child);
                } else if (child instanceof LinearLayout) {
                    List<NumberPicker> result = findNumberPicker((ViewGroup) child);
                    if (result.size() > 0) {
                        return result;
                    }
                }
            }
        }
        return npList;
    }

    public int getYear() {
        return mYear;
    }

    public int getDay() {
        return mDay;
    }

    public int getMonth() {
        //返回的时间是0-11
        return mMonth+1;
    }

    public int getMinute() {
        return mMinute;
    }

    public int getHour() {
        return mHour;
    }

    /**
     * 获取日期选择的值
     */
    private void getDatePickerValue() {
        mYear = mDatePicker.getYear();
        mMonth = mDatePicker.getMonth();
       mDay= mDatePicker.getDayOfMonth();
    }

    /**
     * 获取时间选择的值
     */
    private void getTimePickerValue() {
        // api23这两个方法过时
        mHour = mTimePicker.getCurrentHour();// timePicker.getHour();
        mMinute = mTimePicker.getCurrentMinute();// timePicker.getMinute();
    }



    public interface TimePickerDialogInterface {
        public void positiveListener();
        public void negativeListener();
    }

}


dialog布局:

这是datePicker和timePicker同时显示的时候的布局(这个是横向的适配可能不是很),其他两个没有就不贴了,自己建一个布局写个DatePicker或TimePicker,再或者写在一个布局自己判断调用...


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal"
  android:layout_width="match_parent"
  android:weightSum="2"
  android:gravity="center"
  android:layout_height="match_parent">
    <DatePicker 
        android:id="@+id/datePicker1"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:calendarViewShown="false"
        />
    <TimePicker 
        android:id="@+id/timePicker1"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"/>
</LinearLayout>



这个是纵向的适配会非常容易,推荐使用


<?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:gravity="center"
    android:layout_height="match_parent">
    <DatePicker
        android:id="@+id/dateAndTimePicker_datePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:calendarViewShown="false"
        />
    <TimePicker
        android:id="@+id/dateAndTimePicker_timePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>


使用方法很简单:

1.new出来在activity或fragment定义成全局的变量。

  mTimePickerDialog = new TimePickerDialog(RouteSetOwnerActivity.this);

2.就像这样想显示那个显示那个。

 mTimePickerDialog.showTimePickerDialog();

3.现实TImePickerDialog里面接口,并且重写里面的方法,然后根据自己的 需要来取时间。如下:

public class RouteSetOwnerActivity extends Activity implements TimePickerDialog.TimePickerDialogInterface {
 
   
    private TimePickerDialog mTimePickerDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_route_set_owner);
        mTimePickerDialog = new TimePickerDialog(RouteSetOwnerActivity.this);
      
      
    }

    //时间选择器----------确定
    @Override
    public void positiveListener() {
        int hour = mTimePickerDialog.getHour();
        int minute = mTimePickerDialog.getMinute();
        Log.i("=====","=======year======"+mTimePickerDialog.getYear());
        Log.i("=====","=======getMonth======"+mTimePickerDialog.getMonth());
        Log.i("=====","=======getDay======"+mTimePickerDialog.getDay());
        Log.i("=====","=======getHour======"+mTimePickerDialog.getHour());
        Log.i("=====","=======getMinute======"+mTimePickerDialog.getMinute());
        mTv_getOffWork.setText(hour+":"+minute);
    }

    //时间选择器-------取消
    @Override
    public void negativeListener() {

    }
}




5
2

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:76114次
    • 积分:938
    • 等级:
    • 排名:千里之外
    • 原创:29篇
    • 转载:3篇
    • 译文:0篇
    • 评论:60条
    最新评论