在日历中设置年份和月份

时间:2014-04-27 20:04:05

标签: android eclipse calendar

我正在尝试将日历设置为用户使用2个EditTexts输入的年份和月份,由于某种原因,我没有运气来更改日历。以下是我现在正在处理的方法。有谁知道我哪里出错了?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button change2 = (Button) findViewById(R.id.button1);

    change2.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            change();
        }
    });
}

public void change() {
    Calendar currentDate = GregorianCalendar.getInstance();

    Month = (EditText) findViewById(R.id.editText1);
    Year = (EditText) findViewById(R.id.editText2);

    int newmonth = Integer.parseInt(Month.getText().toString());
    int newyear = Integer.parseInt(Year.getText().toString());

    currentDate.set (Calendar.YEAR, newyear);
    currentDate.set (Calendar.MONTH, newmonth);
}

1 个答案:

答案 0 :(得分:0)

Android-Calendar-API中的月份基于零索引,因此您需要:

public void change() {
  Calendar currentDate = GregorianCalendar.getInstance();

  Month = (EditText) findViewById(R.id.editText1);
  Year = (EditText) findViewById(R.id.editText2);

  int newmonth = Integer.parseInt(Month.getText().toString());
  int newyear = Integer.parseInt(Year.getText().toString());

  currentDate.set (Calendar.YEAR, newyear);
  currentDate.set (Calendar.MONTH, newmonth - 1); // here the change
}

您还应检查您的方法change()是否在合适的听众中调用,请注意OnEditorActionListener。可以在this tutorial上找到如何使用它的示例。

重要更新:

不要忘记使用您的本地变量currentDate来更新您的UI。您将其设置为现在,然后在方法change()结束后将其丢弃。你应该可以google,因为我不是Android专家(只是日历专家)。然而,我发现这两个SO贡献可能会给你一个想法:

setting-the-date-of-a-datepicker-using-the-updatedate-method

how-to-update-the-date-in-datepiker-dialog-android

相关问题