Android小筆記之對話框形式修改日期

    

    以對話框的形式彈出日期設置:


     首先在xml中創建一個EditText輸入框:

        

                

        <EditText

            android:id="@+id/et_time"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            //設置輸入框點擊事件

            android:onClick="dateshow" />

      

    在主方法的onCreate中設置修改時間


    private  EditText time;

        protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

                time = (EditText) findViewById(R.id.et_time);

                Calendar calendar = Calendar.getInstance();

                //獲取日期

newyear = calendar.get(Calendar.YEAR);

                //因爲月份從0--11所以要加1

newmonth = calendar.get(Calendar.MONTH) + 1;

newday = calendar.get(Calendar.DAY_OF_MONTH);

update();



        }

        public void dateshow(View v) {

                //點擊EditText時以對話框形式彈出修改日期

onCreatDialog(DATE_SHOW).show();


}


protected Dialog onCreatDialog(int id) {

switch (id) {

case DATE_SHOW:

return new DatePickerDialog(incomeActivity.this, dateSetListener,

newyear, newmonth, newday);


}


return null;


}


private DatePickerDialog.OnDateSetListener dateSetListener = new OnDateSetListener() {


@Override

public void onDateSet(DatePicker view, int year, int monthOfYear,

int dayOfMonth) {

// TODO Auto-generated method stub

                        //修改年份

newyear = year;

                        //修改月份

newmonth = monthOfYear;

                        //修改日期

newday = dayOfMonth;

update();

}


};


private void update() {

// TODO Auto-generated method stub

                //用於多個字符串的拼接

StringBuffer sb = new StringBuffer();

                //設置修改後的日期時間到EditText中

time.setText(sb.append(newyear).append("-").append(newmonth)

.append("-").append(newday));

}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章