我是Android编码的新手。我正在尝试通过单击按钮来设置日期。我已经阅读并尝试了其他成员在这里发布的大量方法,但每当我点击按钮时,什么都没发生。我的代码有什么问题吗?
public class Date extends Activity {
private TextView tvDisplayDate;
private Button btnDate;
private int year;
private int month;
private int day;
static final int DATE_DIALOG_ID = 999;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setCurrentDateOnView();
addListenerOnButton();
}
// display current date
public void setCurrentDateOnView() {
tvDisplayDate = (TextView) findViewById(R.id.date);
//dpResult = (DatePicker) findViewById(R.id.dpResult);
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// set current date into textview
tvDisplayDate.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" "));
}
public void addListenerOnButton() {
btnDate = (Button) findViewById(R.id.SetDate);
btnDate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
// set date picker as current date
return new DatePickerDialog(this, datePickerListener,
year, month,day);
}
return null;
}
private DatePickerDialog.OnDateSetListener datePickerListener
= new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// set selected date into textview
tvDisplayDate.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
}
};
}
答案 0 :(得分:0)
你确实可以使用Calender类,但我更喜欢使用相同的结果保持简洁和简单。我将向您展示我在其他人的博客上使用过的替代方案。
// Formats are everywhere on the internet.
DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy ");
Calendar cal = Calendar.getInstance();
String output = dateFormat.format(cal.getTime());
System.out.println(output);
只需将System.out.print方法更改为视图的setText即可。
来源:http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/