@Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = inflater.inflate(R.layout.box_grid_item, null); ViewHolder viewHolder = new ViewHolder(); viewHolder.name = (TextView) convertView.findViewById(R.id.box_grid_name); viewHolder.icon = (ImageView) convertView.findViewById(R.id.box_grid_icon); convertView.setTag(viewHolder); } ViewHolder holder = (ViewHolder) convertView.getTag(); Box box = boxes.get(position); holder.icon.setImageBitmap( BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher)); holder.name.setText(box.getName()); return convertView; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_box); GridView grid = (GridView) findViewById(R.id.box_grid); final List<Box> boxes = new ArrayList<Box>(); Box d = new Box(); d.setName("旅行"); d.setIntent(new Intent(this, TravelActivity.class)); boxes.add(d); MyAdapter adapter = new MyAdapter(this, boxes); grid.setAdapter(adapter); grid.setOnItemClickListener( new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(view.getContext(), position + " clicked", Toast.LENGTH_LONG).show(); startActivity(boxes.get(position).getIntent()); } }); }