Android (4) TimePickerDialog 選擇時間
1. 添加一個 Button 和 TextView:
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/timeText" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Time" android:textSize="30sp"/> <Button android:id="@+id/timeButton" /> android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Time" </LinearLayout>
2. Source code:
註冊一個 Listener 到 Button 元件。
public class MainActivity extends AppCompatActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final TextView timeText = (TextView)findViewById(R.id.timeText); final Button timeButton = (Button)findViewById(R.id.timeButton); timeButton.setOnClickListener(new MyTimePicker(timeText)); } }
實做 onClick 和 onTimeSet:
private class MyTimePicker implements View.OnClickListener, TimePickerDialog.OnTimeSetListener { private TextView mTimeText; public MyTimePicker(TextView timeText) { mTimeText = timeText; } @Override public void onClick(View v) { Calendar calendar = Calendar.getInstance(); TimePickerDialog dialog = new TimePickerDialog( MainActivity.this, // context this, // listener calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), false); dialog.show(); } @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { String des = String.format("%s-%s", hourOfDay, minute); mTimeText.setText(des); } }
3. 完整程式碼:
package com.example.ben.androidtest; 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.Button; import android.widget.TextView; import android.widget.TimePicker; public class MainActivity extends AppCompatActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final TextView timeText = (TextView)findViewById(R.id.timeText); final Button timeButton = (Button)findViewById(R.id.timeButton); timeButton.setOnClickListener(new MyTimePicker(timeText)); } private class MyTimePicker implements View.OnClickListener, TimePickerDialog.OnTimeSetListener { private TextView mTimeText; public MyTimePicker(TextView timeText) { mTimeText = timeText; } @Override public void onClick(View v) { Calendar calendar = Calendar.getInstance(); TimePickerDialog dialog = new TimePickerDialog(MainActivity.this, this, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), false); dialog.show(); } @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { String des = String.format("%s-%s", hourOfDay, minute); mTimeText.setText(des); } } }
留言
張貼留言