時間設定調整
1.UI的xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:text="時間設定" />
</RelativeLayout>
2.主程式程式碼
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.TimePickerDialog;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
public class MainActivity extends Activity {
Button btn;
TextView tv;
private int hour, min;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) this.findViewById(R.id.button1);
tv = (TextView) this.findViewById(R.id.textView1);
setDate();
btn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
setTimePickerDialog();
}
});
}
public void setTimePickerDialog() {
TimePickerDialog log = new TimePickerDialog(MainActivity.this, 1,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker arg0, int hour, int min) {
MainActivity.this.hour = hour;
MainActivity.this.min = min;
tv.setText((MainActivity.this.hour < 10 ? "0"
+ MainActivity.this.hour
: MainActivity.this.hour)
+ ":"
+ (MainActivity.this.min < 10 ? "0"
+ MainActivity.this.min
: MainActivity.this.min));
}
}, hour, min, false);
log.show();
}
public void setDate() {
Calendar calendar = Calendar.getInstance();
hour = calendar.get(Calendar.HOUR_OF_DAY);
min = calendar.get(Calendar.MINUTE);
tv.setText((MainActivity.this.hour < 10 ? "0" + MainActivity.this.hour
: MainActivity.this.hour)
+ ":"
+ (MainActivity.this.min < 10 ? "0" + MainActivity.this.min
: MainActivity.this.min));
}
}
沒有留言:
張貼留言