与ListView一维排布相对
public class MainActivity extends Activity implements AdapterView.OnItemClickListener{
private GridView gv;
private int[] icon = {
R.drawable.address_book,R.drawable.calendar,R.drawable.camera,
R.drawable.clock,R.drawable.games_control,R.drawable.messenger,
R.drawable.ringtone,R.drawable.settings,R.drawable.youtube
};
private String[] name = {
"address_book" , "calendar" , "camera" ,
"clock" ,"games_control", "messenger" ,
"ringtone" , "settings" ,"youtube"
};
private List<Map<String,Object>> listdata;
private SimpleAdapter sim_adapter; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //注册控件
gv = (GridView)findViewById(R.id.gridView);
//数据源
listdata = new ArrayList<Map<String,Object>>(); //适配器
sim_adapter = new SimpleAdapter(this,getData(),R.layout.buju,new String[]{"pic", "txt"},new int[]{R.id.pic,R.id.txt}); //GridView与适配器绑定
gv.setAdapter(sim_adapter);
gv.setOnItemClickListener(this); } private List<Map<String,Object>> getData(){
for(int i = 0 ; i < icon.length ; i++){
Map<String,Object> map = new HashMap<String, Object>();
map.put("pic",icon[i]);
map.put("txt",name[i]);
listdata.add(map);
}
return listdata;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(this,"这里是:"+ name[position],Toast.LENGTH_SHORT).show();
}
gridview 三个常用的属性
numcolumns :每一行显示多少列 列数 可以自动适配 auto_fit
horizontalspacing 两列之间的间距 其实翻译过来就是水平之间的距离 就是两列之间的距离
verticalspacing 行距 垂直之间的距离
android:numColumns="3" 分为3列
android:horizontalSpacing="10dp" 每列间距10dp
android:verticalSpacing="10dp" 每行间距10dp
<GridView
android:layout_marginTop="10dp"
android:numColumns="3"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/gridView" />
GridView监听事件 OnItemClickListener