第一步:布局
在layout中新建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/text1"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:gravity="center" />
</LinearLayout>
第二部:编写Java代码
public class MainActivity extends Activity {
private GridView smallImageGrid;
private ImageView showImage;
private int[] pics;
private String[] text1 = new String[6];
@Override
protected 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 i = 0; i < text1.length; i++) {
text1[i] = "第" + (i + 1) + "张图片";
}
for (int i = 0; i < pics.length; i++) {
Map<String, Object> item = new HashMap<String, Object>();
item.put("pic", pics[i]);
item.put("text1", text1[i]);
pic_items.add(item);
}
SimpleAdapter adapter = new SimpleAdapter(this, pic_items,
R.layout.grid, new String[] { "pic", "text1" }, new int[] {
R.id.smallImage, R.id.text1 });
smallImageGrid.setAdapter(adapter);
showImage.setImageResource(pics[0]);
smallImageGrid.setBackgroundResource(R.drawable.bg);
smallImageGrid.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view,
int position, long id) {
// TODO Auto-generated method stub
showImage.setImageResource(pics[position]);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}