【问题标题】:Setting year and month in calendar在日历中设置年份和月份
【发布时间】:2014-04-27 20:04:05
【问题描述】:

我正在尝试将日历设置为用户使用 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);
}

【问题讨论】:

    标签: android eclipse calendar


    【解决方案1】:

    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() 结束后将其丢弃。你应该可以用谷歌搜索,因为我不是 Android 专家(只是日历专家)。然而,我发现这两个 SO-contributions 可能会给你一个想法:

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

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

    【讨论】:

    • 您好,您建议我进行更改,但在更改日历方面仍然没有做任何事情。
    • 我已经编辑了问题以包括我的 oncreate 方法,我不确定它是否与听众有关。
    • @Mark101 请看我的更新。你最终将如何处理变量currentDate?
    • 我不确定如何更新它,我试图研究如何更新但没有运气。我看到的所有示例都停在 currentDate.set 行。
    • @Mark101 我添加了两个 SO 链接,希望对您有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多