DatePicker 和 TimePicker使用

效果图:

imageimage

例子包含一个Main.java文件和一个  xml布局文件,由于xml布局文件只包含两个按钮,顾不在给出!

程序代码如下:

public class Main extends Activity {
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button date = (Button) findViewById(R.id.btn);
        Button time = (Button) findViewById(R.id.btn1);
        date.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Calendar c = Calendar.getInstance();
                // 创建日期对话框
                new DatePickerDialog(Main.this,
                        new DatePickerDialog.OnDateSetListener() {
                            public void onDateSet(DatePicker arg0, int year,
                                    int month, int day) {
 
                                show(year + "年" + month + "月" + day + "日");
                            }
                        },
                        // 初始化日期
                        c.get(Calendar.YEAR), c.get(Calendar.MONTH), c
                                .get(Calendar.DAY_OF_MONTH)).show();
 
            }
        });
        time.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Calendar c = Calendar.getInstance();
                new TimePickerDialog(Main.this,
                        new TimePickerDialog.OnTimeSetListener() {
 
                            public void onTimeSet(TimePicker view,
                                    int hourOfDay, int minute) {
                                show(hourOfDay + "点" + minute + "分");
 
                            }
                        }, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE),
                        false).show();
 
            }
        });
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
 
    private void show(String s) {
        Toast.makeText(Main.this, s, Toast.LENGTH_SHORT).show();
    }
}
posted @ 2012-11-16 16:37  高捍得  阅读(249)  评论(0编辑  收藏  举报