การตั้งปีและเดือนในปฏิทิน

ฉันกำลังพยายามตั้งค่าปฏิทินเป็นปีและเดือนที่ผู้ใช้ป้อนโดยใช้ 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);
}

person Mark101    schedule 27.04.2014    source แหล่งที่มา


คำตอบ (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 ตัวอย่างวิธีใช้งานสามารถพบได้ในบทแนะนำนี้ .

การอัปเดตที่สำคัญ:

อย่าลืมใช้ตัวแปรในเครื่อง currentDate เพื่ออัปเดต UI ของคุณ คุณตั้งค่าไว้จนถึงขณะนี้ แล้วคุณทิ้งมันไปหลังจากสิ้นสุดวิธี change() คุณควรใช้ Google เนื่องจากฉันไม่ใช่ผู้เชี่ยวชาญด้าน Android (เป็นเพียงผู้เชี่ยวชาญด้านปฏิทิน) อย่างไรก็ตาม ฉันได้พบการมีส่วนร่วม SO ทั้งสองนี้ซึ่งอาจให้แนวคิดแก่คุณ:

setting-the-date-of-a-datepicker- ใช้-the-update-method

how-to-update-the-date-in-datepiker- กล่องโต้ตอบ-Android

person Meno Hochschild    schedule 28.04.2014
comment
สวัสดี ฉันได้เปลี่ยนแปลงตามที่คุณแนะนำแล้ว แต่ยังไม่ได้ทำอะไรเลยในแง่ของการเปลี่ยนปฏิทิน - person Mark101; 29.04.2014
comment
ฉันได้แก้ไขคำถามเพื่อรวมวิธี oncreate ของฉันด้วย ฉันไม่แน่ใจว่าเกี่ยวข้องกับผู้ฟังหรือไม่ - person Mark101; 29.04.2014
comment
@ Mark101 ดูการอัปเดตของฉันได้โปรด ในที่สุดคุณจะทำอย่างไรกับตัวแปร currentDate? - person Meno Hochschild; 29.04.2014
comment
ฉันไม่แน่ใจว่าจะอัปเดตได้อย่างไร ฉันพยายามค้นหาวิธีการแต่ก็ไม่มีโชค ตัวอย่างทั้งหมดที่ฉันเคยเห็นหยุดที่บรรทัด currentDate.set - person Mark101; 29.04.2014
comment
@ Mark101 ฉันได้เพิ่ม SO-link สองอันซึ่งหวังว่าจะช่วยคุณได้ - person Meno Hochschild; 29.04.2014
comment
เฮ้ ขออภัยที่ตอบช้า ฉันดูลิงก์แล้ว แต่ฉันยังคงสับสนกับสิ่งที่ฉันหายไป - person Mark101; 01.05.2014