GridViewDemo.java package com.example.gridviewdemo;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.view.ViewGroup;import android.widget.AdapterView;import android.widget.BaseA
package com.example.gridviewdemo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class GridViewDemo extends AppCompatActivity { private int[] imgids = {R.drawable.apple_pic, R.drawable.banana_pic, R.drawable.cherry_pic, R.drawable.grape_pic, R.drawable.mango_pic, R.drawable.orange_pic, R.drawable.pear_pic, R.drawable.strawberry_pic, R.drawable.watermelon_pic}; private String[] name = {"苹果", "香蕉", "樱桃", "葡萄", "芒果", "橙子", "梨", "草莓", "西瓜"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_grid_view_demo); GridView gv = (GridView) findViewById(R.id.gv); gv.setAdapter(new MyAdapter()); gv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { Toast.makeText(GridViewDemo.this,name[position],Toast.LENGTH_SHORT).show(); } }); } public class MyAdapter extends BaseAdapter { @Override public int getCount() { return name.length; } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = View.inflate(GridViewDemo.this, R.layout.gv_item, null); ImageView iv=view.findViewById(R.id.iv); iv.setImageResource(imgids[position]); TextView tv=view.findViewById(R.id.tv); tv.setText(name[position]); return view; } } }activity_grid_view_demo.xml
gv_item.xml