Android UI设计 时间控件TimePicker用法(含取值)

TimePicker是android系统里的时间控件,我们可以通过这个控件让用户输入合法的时间,很方便。
下面是效果图:

具体代码:
布局main.xml:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  android:id="@+id/tv"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text=""
    />
<TimePicker android:id="@+id/tp"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
/>
<Button android:id="@+id/b1"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:text="显示在标题栏"
/>
</LinearLayout>

程序代码:


package com.pocketdigi;

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

public class main extends Activity {
    /** Called when the activity is first created. */
	TextView tv;
	TimePicker tp;
	Button b1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TPDemo();
    }
    public void TPDemo(){
        tp=(TimePicker)findViewById(R.id.tp);
        tp.setIs24HourView(true);//是否显示24小时制?默认false
        tp.setCurrentHour(6);
        tp.setCurrentMinute(20);
        //设置显示时间为6:20
        tp.setOnTimeChangedListener(tpLis);
        //时间改变时触发
        tv=(TextView)findViewById(R.id.tv);
        b1=(Button)findViewById(R.id.b1);
        b1.setOnClickListener(b1Lis);   	
    }
    private OnTimeChangedListener tpLis=new OnTimeChangedListener() {   
    	public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {   
            tv.setText("[" + hourOfDay + ":" + minute + "]" + "["  
                    + view.getCurrentHour() + ":" + view.getCurrentMinute()   
                    + "]");   

        }   
    }; //时间改变后执行的内容,用两种方式显示在tv上
    private OnClickListener b1Lis=new OnClickListener(){
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			setTitle(tp.getCurrentHour()+":"+tp.getCurrentMinute());
		}   	
    };//单击按钮后执行的内容,显示时间在标题上
}

© 2010, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记