我想在 android 中使用 GridView 创建一个月历。这是我的代码:(对不起我的命名)活动类:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_month_calendar);
GridView calendar = (GridView) findViewById(R.id.month_view);
final List<Item> items = new ArrayList<Item>();
Item item;
for (int i = 0; i < 42; i++) {
item = new Item();
item.setDay(String.valueOf(i + 1));
items.add(item);
}
List<String> yoteis = new ArrayList<String>();
yoteis.add("Go to beach");
items.get(15).setYotei(yoteis);
final MonthCalendarAdapter adapter = new MonthCalendarAdapter(this, items);
calendar.setAdapter(adapter);
calendar.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int pos,
long id) {
Toast.makeText(MonthCalendarActivity.this, "" + pos, Toast.LENGTH_SHORT).show();
List<String> newYoteis = new ArrayList<String>();
newYoteis.add("new yotei");
items.get(pos).setYotei(newYoteis);
adapter.notifyDataSetChanged();
}
});
}
适配器:
List<Item> items;
Context mContext;
public MonthCalendarAdapter(Context context,
List<Item> objects) {
super(context, 0, objects);
mContext = context;
items = objects;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
MonthCell cell;
LayoutParams params = new GridView.LayoutParams(65,80);
if(convertView == null) {
cell = new MonthCell(mContext, items.get(position));
cell.setLayoutParams(params);
cell.setScaleType(ImageView.ScaleType.CENTER_CROP);
}else {
convertView.setLayoutParams(params);
cell = (MonthCell) convertView;
}
return cell;
}
MonthCell 类:
public class MonthCell extends ImageView {
Paint paint;
Item item;
public MonthCell(Context context) {
super(context);
paint = new Paint();
}
public MonthCell(Context context, Item item) {
this(context);
this.item = item;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(Color.rgb(0, 176, 240));
canvas.drawText(item.getDay(), 10, 20, paint);
List<String> yoteis = item.getYotei();
if(yoteis != null) {
if(!yoteis.isEmpty()) {
setBackgroundResource(R.drawable.cell);
paint.setColor(Color.rgb(255, 124, 128));
for(int i = 0; i < yoteis.size(); i++) {
canvas.drawText(yoteis.get(i), 10, 20 * (i + 2), paint);
}
}
}
}
}
第一次加载Activity,画面是这样的:
1 2 3 4 5 6 7
8 9 10 ....
但是当我点击日历时,顺序变成了这样:
42 41 40 39 ....
……
7 6 5 4 3 2 1
(对不起,我不能上传图片,因为我没有足够的声誉) 谁能向我解释为什么会发生这种情况以及如何解决它。提前致谢!