下面直接通过一个例子讲解GridView的用法。
mian.xml文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<!--定义一个4列的GridView控件 -->
<GridView
android:id="@+id/gridView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:numColumns="4" >
</GridView>
<!-- 定义一个ImageView -->
<ImageView
android:id="@+id/main_im"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="@drawable/bomb1"
android:layout_weight="1.5" />
</LinearLayout>
在定义一个cell.xml文件,里面只有一个ImageView。
<?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/p_w_picpathView1"
android:layout_width="50dip"
android:layout_height="50dip"
/>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
/**
* @author shao
*使用SimpleAdapter为GridView控件添加内容
*/
private GridView gd;
private ImageView p_w_picpathView;
private SimpleAdapter simpleAdapter;
private int[] p_w_picpathId = { R.drawable.bomb1, R.drawable.bomb2,
R.drawable.bomb3, R.drawable.bomb4, R.drawable.bomb5,
R.drawable.bomb6, R.drawable.bomb7, R.drawable.bomb8,
R.drawable.bomb9, R.drawable.bomb10, R.drawable.bomb11,
R.drawable.bomb12};
private List<Map<String, Object>> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//查找控件
gd = (GridView) findViewById(R.id.gridView1);
p_w_picpathView = (ImageView) findViewById(R.id.main_im);
//为list添加内容
list = new ArrayList<Map<String, Object>>();
for (int i = 0; i < p_w_picpathId.length; i++) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("p_w_picpath", p_w_picpathId[i]);
list.add(map);
}
simpleAdapter = new SimpleAdapter(this, list, R.layout.cell,
new String[] { "p_w_picpath" }, new int[] { R.id.p_w_picpathView1 });
//为GridView控件添加Adapter
gd.setAdapter(simpleAdapter);
//为GridView控件添加监听
gd.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
p_w_picpathView.setImageResource(p_w_picpathId[position]);
}
});
}
}
运行效果,当点击不同过得图片时,屏幕的下方将显示相应的图片