Android日期时间选择器DatePicker、TimePicker日期时间改变事件响应(Android学习笔记)

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/input"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="datetime" />

    <LinearLayout
        android:id="@+id/LinearLayout2"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal" >
        <DatePicker
            android:id="@+id/mydp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TimePicker
            android:id="@+id/mytp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

</LinearLayout>

 

MainActivity.java

public class MainActivity extends Activity {
    private EditText myInput=null;
    private TimePicker mytp=null;
    private DatePicker mydp=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.myInput=(EditText)super.findViewById(R.id.input);
        this.mytp=(TimePicker)super.findViewById(R.id.mytp);
        this.mydp=(DatePicker)super.findViewById(R.id.mydp);
        this.mytp.setIs24HourView(true);//设置为24小时制
        this.mytp.setOnTimeChangedListener(new OnTimeChangedListenerImpl());//添加时间变更响应事件
        this.mydp.init(this.mydp.getYear(), 
                this.mydp.getMonth(), 
                this.mydp.getDayOfMonth(), 
                new OnDateChangeLinstenerImpl());//添加日期变更响应事件
        this.setDateTime(); //设置初始的日期事件
    }
    private class OnTimeChangedListenerImpl implements OnTimeChangedListener{

        @Override
        public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
            // 当时间改变时触发的事件
            setDateTime();
        }
        
    }
    
    private class OnDateChangeLinstenerImpl implements OnDateChangedListener{

        @Override
        public void onDateChanged(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            // 当日期改变时触发的事件
            setDateTime();
        }
        
    }
    
    public void setDateTime(){
        this.myInput.setText(this.mydp.getYear()+"-"+(this.mydp.getMonth()+1)+"-"+this.mydp.getDayOfMonth()+" "+this.mytp.getCurrentHour()+":"+this.mytp.getCurrentMinute());
    }

 

posted @ 2013-09-27 14:56  寂静之秋  阅读(2069)  评论(0编辑  收藏  举报
哈尔滨八零网