20170124 AlertDialgo(加入日期和時間交談窗)
用DatePickerDialog和TimePickerDialog
類別建立日期和時間交談窗
//20170124 劉彥廷
//AlertDialgo(加入日期和時間交談窗)
MainActivity.java
package com.example.user.myapplication44;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.icu.util.Calendar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
public class MainActivity extends AppCompatActivity
implements View.OnClickListener,
DatePickerDialog.OnDateSetListener,
TimePickerDialog.OnTimeSetListener{
Calendar c = Calendar.getInstance();
TextView txDate,txTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txDate = (TextView)findViewById(R.id.textView1);
txTime = (TextView)findViewById(R.id.textView2);
txDate.setOnClickListener(this);
txTime.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v==txDate){
new DatePickerDialog(this,this,
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH))
.show();
}
else if(v ==txTime){
new TimePickerDialog(this,this,
c.get(Calendar.HOUR_OF_DAY),
c.get(Calendar.MINUTE),
true)
.show();
}
}
@Override
public void onDateSet(DatePicker v, int y, int m, int d) {
txDate.setText("日期:"+y+ "/"+(m+1)+"/"+d); //將選定事情顯示在螢幕上
}
@Override
public void onTimeSet(TimePicker v, int h, int m) {
txTime.setText("時間:"+h+":"+m); //將選定事情顯示在螢幕上
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.user.myapplication44.MainActivity"
android:orientation="vertical">
<TextView
android:text="@string/TextView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textView1"
android:textSize="26sp" />
<TextView
android:text="@string/TextView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textView2"
android:textSize="26sp" />
</LinearLayout>
strings.xml
<resources>
<string name="app_name">AlertDialgo(加入日期和時間交談窗) (No44)</string>
<string name="TextView1">日期:未設定</string>
<string name="TextView2">時間:未設定</string>
</resources>
留言
張貼留言