android 之GridView 的使用
源文引入找不到地址了,在此做一个代码的备份,方使以后使用。
先看一下效果图吧,
首先:看一样main.xml布局代码
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/bg" > <GridView android:id="@+id/gridview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:numColumns="3"/> </LinearLayout>
注:用以用到一展图片。bg.png
然后是每一个选项目的gridviewitem.xml 布局代码 ,用于展示每个选项的图标和名称
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:scrollbars="vertical"> <ImageView android:layout_height="100dip" android:id="@+id/ItemImage" android:layout_width="80dip" android:src="@drawable/png1" android:layout_gravity="center_horizontal"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:id="@+id/ItemText" /> </LinearLayout>
注:用以用到一展图片。png1.png
MainActivity.java
package net.csdn.blog.androidtoast; import java.util.ArrayList; import java.util.HashMap; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import android.widget.SimpleAdapter; import android.widget.Toast; public class MainActivity extends Activity { /** Called when the activity is first created. */ //定义图片整型数组 private int[] mImages={ R.drawable.png1, R.drawable.png2, R.drawable.png3, R.drawable.png4, R.drawable.png5, R.drawable.png6, R.drawable.png7, R.drawable.png8, R.drawable.png9 }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //实例化GridView GridView mGridView=(GridView) findViewById(R.id.gridview); // 生成动态数组,并且传入数据 ArrayList<HashMap<String, Object>> lstImageItem = new ArrayList<HashMap<String, Object>>(); for (int i = 0; i < 9; i++) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("ItemImage", mImages[i]);// 添加图像资源的ID map.put("ItemText", "NO." + String.valueOf(i+1));// 按序号做ItemText lstImageItem.add(map); } //构建一个适配器 SimpleAdapter simple = new SimpleAdapter(this, lstImageItem, R.layout.gridviewitem, new String[] { "ItemImage", "ItemText" }, new int[] { R.id.ItemImage, R.id.ItemText }); mGridView.setAdapter(simple); //添加选择项监听事件 mGridView.setOnItemClickListener(new GridView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view,int position, long id) { Toast toast=Toast.makeText(getApplicationContext(), "你选择了"+(position+1)+"号图片", 1); toast.setGravity(Gravity.BOTTOM, 0, 0); toast.show(); } }); } }