日期选择控件

布局文件:

<RelativeLayout android:id="@+id/date_picker"
    android:layout_width="wrap_content" android:layout_height="wrap_content">
        <TextView android:id="@+id/birthday_text" android:editable="false"
             android:layout_width="wrap_content" android:layout_height="wrap_content"
             android:textColor="#000000" android:textSize="24sp" android:background="@drawable/text_bg"/>
         <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content"
             android:background="@drawable/date_select_icon" android:layout_alignRight="@id/birthday_text"
             android:layout_centerVertical="true" android:layout_marginRight="8dp"/>
</RelativeLayout>
  
public class TestActivity extends Activity {

private int mYear;
private int mMonth;
private int mDay;
static final int DATE_DIALOG_ID = 1;

TextView date;

 

@Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);

        date = (TextView) findViewById(R.id.birthday_text);
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        RelativeLayout datePicker = (RelativeLayout) findViewById(R.id.date_picker);
        datePicker.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:
            return new DatePickerDialog(TestActivity.this, mDateSetListener,
                    mYear, mMonth, mDay);
        }
        return null;
  }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {
        case DATE_DIALOG_ID:
            ((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
            break;
        }
 }

private DatePickerDialog.OnDateSetListener mDateSetListener = new   DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            date.setText(mYear + "-" + (mMonth + 1) + "-" + mDay);
        }
 };

}

相关推荐