下面有一个简单的适配器示例Spinner
。
public class CalendarSpinnerAdapter extends BaseAdapter {
private SimpleDateFormat mDateFormat = new SimpleDateFormat("d MMM yyyy");
private LayoutInflater mInflater;
private Calendar mCalendar;
private int mDayCount;
private int mLastRequestedDay = 0;
public CalendarSpinnerAdapter(Context context, int dayCount) {
mInflater = LayoutInflater.from(context);
mDayCount = dayCount;
mCalendar = Calendar.getInstance();
}
@Override
public int getCount() {
return mDayCount;
}
@Override
public Calendar getItem(int position) {
mCalendar.add(Calendar.DAY_OF_YEAR, position - mLastRequestedDay);
mLastRequestedDay = position;
return mCalendar;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(android.R.layout.simple_spinner_dropdown_item, parent, false);
}
Calendar item = getItem(position);
((TextView) convertView).setText(mDateFormat.format(item.getTimeInMillis()));
return convertView;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return getView(position, convertView, parent);
}
}
如何使用它来显示当前日期和接下来的 29 天:
mDateSpinner.setAdapter(new CalendarSpinnerAdapter(getActivity(), 30));
升级版:
我们应该在适配器的构造函数中添加一个参数来设置开始日期:
public CalendarSpinnerAdapter(Context context, Calendar startDate, int dayCount) {
mInflater = LayoutInflater.from(context);
mDayCount = dayCount;
mCalendar = Calendar.getInstance();
mCalendar.setTimeInMillis(startDate.getTimeInMillis());
}
spinnerDateIn
然后为我们可以初始化第二个微调器的位置添加监听器:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_date);
Spinner spinnerDateIn = (Spinner) findViewById(R.id.spinnerDateIn);
final Spinner spinnerDateOut = (Spinner) findViewById(R.id.spinnerDateOut);
mSpinnerDateInAdapter = new CalendarSpinnerAdapter(SpinnerDateActivity.this, Calendar.getInstance(), 30);
spinnerDateIn.setAdapter(mSpinnerDateInAdapter);
spinnerDateIn.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Calendar dateIn = Calendar.getInstance();
dateIn.setTimeInMillis(mSpinnerDateInAdapter.getItem(position).getTimeInMillis());
dateIn.add(Calendar.DAY_OF_YEAR, 1); // add one day
mSpinnerDateOutAdapter = new CalendarSpinnerAdapter(SpinnerDateActivity.this, dateIn, 30);
spinnerDateOut.setAdapter(mSpinnerDateOutAdapter);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
我没有尝试此代码,但它应该可以工作。
UPD2:
spinnerDate.setSelection(position)
返回Calendar
类实例。如果你想获得选定的日期,String
你应该格式化它。尝试使用以下方法:
private String getSelectedDateAsString(Spinner dateSpinner) {
Calendar selectedDate = (Calendar) dateSpinner.getSelectedItem();
return new SimpleDateFormat("d MMM yyyy").format(selectedDate.getTimeInMillis());
}