日期設定調整
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.DatePickerDialog;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
public class MainActivity extends Activity {
Button btn;
TextView tv;
private int year, month, date;
@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) {
setDatePickerDialog();
}
});
}
public void setDatePickerDialog() {
DatePickerDialog log = new DatePickerDialog(MainActivity.this, 1,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0, int year, int month,int date) {
MainActivity.this.year = year;
MainActivity.this.month = month+1;
MainActivity.this.date = date;
tv.setText(MainActivity.this.year + "-"
+ (MainActivity.this.month < 10 ? "0" + MainActivity.this.month :MainActivity.this.month) + "-"
+ (MainActivity.this.date < 10 ? "0" + MainActivity.this.date : MainActivity.this.date));
}
}, year, month, date);
log.show();
}
public void setDate() {
Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
date = calendar.get(Calendar.DATE);
tv.setText(year + "-" + (month < 10 ? "0" + (month+1) : (month+1)) + "-"
+ (date < 10 ? "0" + date : date));
}
}
沒有留言:
張貼留言