页面
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<GridView
android:id="@+id/imagelist"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:horizontalSpacing="20dp"
android:numColumns="2"
android:verticalSpacing="10dp" >
</GridView>
<ImageView
android:id="@+id/imageshow"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
/>
</LinearLayout>
grid.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/smallImage"
android:layout_width="80dp"
android:layout_height="50dp" />
<TextView
android:id="@+id/text_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/smallImage" >
</TextView>
</LinearLayout>
主要代码MainActivity.java:
public class MainActivity extends Activity {private GridView smallImageGrid;
private ImageView showImage;
private int[] pics;// 存放图片id的数组
private int i = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 查找组件
smallImageGrid = (GridView) this.findViewById(R.id.imagelist);
showImage = (ImageView) this.findViewById(R.id.imageshow);
// 第一步 实例化图片ID的数组
pics = new int[] { R.drawable.a, R.drawable.b, R.drawable.c,
R.drawable.d, R.drawable.e, R.drawable.f };
// 第二步 创建一个List<Map>集合,用于将图片ID转换为List集合
List<Map<String, Object>> pic_items = new ArrayList<Map<String, Object>>();
for (int pic_id : pics) {
Map<String, Object> item = new HashMap<String, Object>();
item.put("pic", pic_id);
i = i + 1;
item.put("textItem", "第" + i + "幅图");
pic_items.add(item);
}
// 第三步 创建SimpleAdaper适配器,以备与GridView组件进行绑定
SimpleAdapter adapter = new SimpleAdapter(this, pic_items,
R.layout.grid, new String[] { "pic", "textItem" }, new int[] {
R.id.smallImage, R.id.text_item });
// 第四步 GridView组件与adapter适配器进行绑定
smallImageGrid.setAdapter(adapter);
// 第五步 为showImage组件设置默认图片
showImage.setImageResource(pics[0]);
// 第六步 注册事件监听
smallImageGrid.setOnItemClickListener(new GridViewHandler());
}
public class GridViewHandler implements OnItemClickListener {
/**
* AdapterView adpaterview:发生点击事件的AdapterView; View
* view:AdapterView中被用户点击的Item(GridView中的Item); int
* positon:被点击的Item在Adapter中的位置 long id:被点击的Item的Id
*/
@Override
public void onItemClick(AdapterView<?> adapter, View view,
int position, long id) {
showImage.setImageResource(pics[position]);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
运行程序效果图如图: