-
MainActivity.java
-
-
public class MainActivity extends Activity
-
{
-
@Override
-
public void onCreate(Bundle savedInstanceState)
-
{
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.main);
-
Button dateBn = (Button)findViewById(R.id.dateBn);
-
Button timeBn = (Button)findViewById(R.id.timeBn);
-
//为"设置日期"按钮绑定监听器
-
dateBn.setOnClickListener(new OnClickListener()
-
{
-
@Override
-
public void onClick(View source)
-
{
-
Calendar c = Calendar.getInstance();
-
// 直接创建一个DatePickerDialog对话框实例,并将它显示出来
-
new DatePickerDialog(MainActivity.this,
-
// 绑定监听器
-
new DatePickerDialog.OnDateSetListener()
-
{
-
@Override
-
public void onDateSet(DatePicker dp, int year,
-
int month, int dayOfMonth)
-
{
-
EditText show = (EditText) findViewById(R.id.show);
-
show.setText("您选择了:" + year + "年" + (month + 1)
-
+ "月" + dayOfMonth + "日");
-
}
-
}
-
//设置初始日期
-
, c.get(Calendar.YEAR)
-
, c.get(Calendar.MONTH)
-
, c.get(Calendar.DAY_OF_MONTH)).show();
-
}
-
});
-
//为"设置时间"按钮绑定监听器
-
timeBn.setOnClickListener(new OnClickListener()
-
{
-
@Override
-
public void onClick(View source)
-
{
-
Calendar c = Calendar.getInstance();
-
// 创建一个TimePickerDialog实例,并把它显示出来
-
new TimePickerDialog(MainActivity.this,
-
// 绑定监听器
-
new TimePickerDialog.OnTimeSetListener()
-
{
-
@Override
-
public void onTimeSet(TimePicker tp, int hourOfDay,
-
int minute)
-
{
-
EditText show = (EditText) findViewById(R.id.show);
-
show.setText("您选择了:" + hourOfDay + "时"
-
+ minute + "分");
-
}
-
}
-
//设置初始时间
-
, c.get(Calendar.HOUR_OF_DAY)
-
, c.get(Calendar.MINUTE)
-
//true表示采用24小时制
-
, true).show();
-
}
-
});
-
}
-
}
-
-
XML文件
-
-
<?xml version="1.0" encoding="utf-8"?>
-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-
android:orientation="vertical"
-
android:layout_width="match_parent"
-
android:layout_height="match_parent"
-
android:gravity="center">
-
<EditText
-
android:id="@+id/show"
-
android:layout_width="match_parent"
-
android:layout_height="wrap_content"
-
android:editable="false"
-
/>
-
<LinearLayout
-
android:orientation="horizontal"
-
android:layout_width="match_parent"
-
android:layout_height="wrap_content"
-
android:gravity="center"
-
>
-
<Button
-
android:id="@+id/dateBn"
-
android:layout_width="wrap_content"
-
android:layout_height="wrap_content"
-
android:text="设置日期"
-
/>
-
<Button
-
android:id="@+id/timeBn"
-
android:layout_width="wrap_content"
-
android:layout_height="wrap_content"
-
android:text="设置时间"
-
/>
-
</LinearLayout>
-
</LinearLayout>