主要代码:
MainActivitiy:
package com.example.gridview;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
public class MainActivity extends Activity {
private GridView smallImageGrid;
private ImageView showImage;
private int[] pics;
@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);
//实例化图片数组
pics=new int[]{R.drawable.a,R.drawable.b,R.drawable.c,R.drawable.d,R.drawable.e,R.drawable.f};
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);
pic_items.add(item);
}
SimpleAdapter adapter=new SimpleAdapter(this,pic_items,R.layout.grid,new String[]{"pic"},new int[]{R.id.smallImage});
smallImageGrid.setAdapter(adapter);
showImage.setImageResource(pics[0]);
smallImageGrid.setOnItemClickListener(new GridViewHandler());
}
public class GridViewHandler implements OnItemClickListener{
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;
}
}
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="3"
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"/>
</LinearLayout>
strings.xml
<resources>
<string name="app_name">GridView组件的使用</string>
<string name="hello_world"> Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">图片展示</string>
</resources>
主要运行图: