TimePicker 时间的获取

TimePicker 时间的获取_第1张图片

通过TimePicker 获取时间,如图所示。当1、转动时间时输出当前的时间;2、点击按钮时获取当前TimePicker的时间


xml代码如下



    
    

Java 代码如下

package com.example.test1;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;

public class MainActivity extends Activity {

	private TimePicker firstTimePicker;
	private Button button;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		firstTimePicker = (TimePicker)findViewById(R.id.firstTimePicker);
		button = (Button)findViewById(R.id.button);
        
		firstTimePicker.setIs24HourView(true);
        TimeListener timeListener = new TimeListener();
        firstTimePicker.setOnTimeChangedListener(timeListener);
        
        ButtonListener buttonListener=new ButtonListener();
        button.setOnClickListener(buttonListener);
		
	}
	class TimeListener implements OnTimeChangedListener{

		@Override
		public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
			// TODO Auto-generated method stub
			System.out.println("hour is "+hourOfDay+" minute is "+minute);
		}
		
	}
	class ButtonListener implements android.view.View.OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			int hour = firstTimePicker.getCurrentHour();
			int minute = firstTimePicker.getCurrentMinute();
			System.out.println("当前时间为"+hour+":"+minute);
		}

	
		}
		
}

可以用setIs24Hour(true)方法设定为24小时制。


你可能感兴趣的:(Android)