我是Android新手,所以请原谅这么简单的问题。如何在 Android 日期选择器中仅设置月份和年份?我不想要里面的日期。请帮助解决这个问题。
问问题
14682 次
2 回答
2
据我所知,你不能用默认的日期选择器来做
于 2012-09-17T10:31:26.333 回答
2
这是仅包含月份和年份的自定义日期选择器的代码。在这里,我通过单击编辑文本框打开了日期选择器。
public class MainActivity extends Activity {
static final int DATE_DIALOG_ID = 1;
private int mYear = 2013;
private int mMonth = 5;
private int mDay = 30;
private EditText etPickADate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etPickADate = (EditText) findViewById(R.id.et_datePicker);
etPickADate.setOnClickListener(new OnClickListener() {
@SuppressWarnings("deprecation")
@Override
public void onClick(View arg0) {
showDialog(DATE_DIALOG_ID);
}
});
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
}
DatePickerDialog.OnDateSetListener mDateSetListner = new OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDate();
}
};
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
/*
* return new DatePickerDialog(this, mDateSetListner, mYear, mMonth,
* mDay);
*/
DatePickerDialog datePickerDialog = this.customDatePicker();
return datePickerDialog;
}
return null;
}
@SuppressWarnings("deprecation")
protected void updateDate() {
int localMonth = (mMonth + 1);
String monthString = localMonth < 10 ? "0" + localMonth : Integer
.toString(localMonth);
String localYear = Integer.toString(mYear).substring(2);
etPickADate.setText(new StringBuilder()
// Month is 0 based so add 1
.append(monthString).append("/").append(localYear).append(" "));
showDialog(DATE_DIALOG_ID);
}
private DatePickerDialog customDatePicker() {
DatePickerDialog dpd = new DatePickerDialog(this, mDateSetListner,
mYear, mMonth, mDay);
try {
Field[] datePickerDialogFields = dpd.getClass().getDeclaredFields();
for (Field datePickerDialogField : datePickerDialogFields) {
if (datePickerDialogField.getName().equals("mDatePicker")) {
datePickerDialogField.setAccessible(true);
DatePicker datePicker = (DatePicker) datePickerDialogField
.get(dpd);
Field datePickerFields[] = datePickerDialogField.getType()
.getDeclaredFields();
for (Field datePickerField : datePickerFields) {
if ("mDayPicker".equals(datePickerField.getName())
|| "mDaySpinner".equals(datePickerField
.getName())) {
datePickerField.setAccessible(true);
Object dayPicker = new Object();
dayPicker = datePickerField.get(datePicker);
((View) dayPicker).setVisibility(View.GONE);
}
}
}
}
} catch (Exception ex) {
}
return dpd;
}
}
于 2013-06-04T04:16:24.863 回答