TimePickerDialog、TimePicker、DatePickerDialog、DatePicker用法

  四个类中不带Dialog的都是对应的控件,带Dialog是相应的弹出的对话框,比如完成设置闹钟或者选择生日等应用中会用到。下面以TimePickerDialog为例介绍2中设置时间的方法:

1、谷歌sdk文档piker中介绍的一种方法:

  <1>构建自己的Dilog类:    

package com.example.user.spinnertest2;

import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TimePicker;

import java.util.Calendar;

/**
 * Created by user on 2016/10/12.
 */
//千万别导错了包
public  class TimePickerFragment extends DialogFragment
        implements TimePickerDialog.OnTimeSetListener {

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

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(getActivity(), this, hour, minute,
                DateFormat.is24HourFormat(getActivity()));
    }
    @Override//执行选择时间后的操作
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        // Do something with the time chosen by the user

        System.out.println("成功"+hourOfDay+"haha"+minute);
    }

}

  需要注意继承导入的包必须是import android.support.v4.app.DialogFragment;之前导入错误导致后面的主函数

timePickerFragment.show(getSupportFragmentManager(), "af")显示dialog时候总是出错,这主要是要兼容3.0前的设置

/要修改相应的activity继承android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity {// AppCompatActivity

    private TimePickerFragment timePickerFragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        timePickerFragment = new TimePickerFragment();
        //显示dialog
        timePickerFragment.show(getSupportFragmentManager(), "af");
        
    }

    }

  这里需要注意的是:修改显示dialog的activity继承android.support.v4.app.FragmentActivity;

2、直接创建dialog

 

        TimePickerDialog timePickerDialog =new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener(){

            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                System.out.println("成功"+hourOfDay+"haha"+minute);
            }
        },  6, 60 ,
        true); //构造设置的时间为默认的时间
        timePickerDialog.show();

 

  

 

posted @ 2016-10-12 17:04  Lammy  阅读(3706)  评论(0编辑  收藏  举报