android元件GridView簡單使用

語言: CN / TW / HK

GridView與ListView的用法基本一致,不同的只是佈局。當我們開啟手機,應用會以宮格顯示,那就是GridView。 以程式碼形式展示給大家,介面卡使用SimpleAdapter,熟悉了介面卡的用法,就只需要注意幾個GridView的屬性即可。

Activity類

```java public class MainActivity extends Activity { private GridView gridView; private List> dataList; private SimpleAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    gridView = (GridView) findViewById(R.id.gridview);
    //初始化資料
    initData();

    String[] from={"img","text"};

    int[] to={R.id.img,R.id.text};

    adapter=new SimpleAdapter(this, dataList, R.layout.gridview_item, from, to);

    gridView.setAdapter(adapter);

    gridView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
        AlertDialog.Builder builder= new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("提示").setMessage(dataList.get(arg2).get("text").toString()).create().show();
        }
    });
}

void initData() {
    //圖示
    int icno[] = { R.drawable.i1, R.drawable.i2, R.drawable.i3,
            R.drawable.i4, R.drawable.i5, R.drawable.i6, R.drawable.i7,
            R.drawable.i8, R.drawable.i9, R.drawable.i10, R.drawable.i11, R.drawable.i12 };
    //圖示下的文字
    String name[]={"時鐘","訊號","寶箱","秒鐘","大象","FF","記事本","書籤","印象","商店","主題","迅雷"};
    dataList = new ArrayList<Map<String, Object>>();
    for (int i = 0; i <icno.length; i++) {
        Map<String, Object> map=new HashMap<String, Object>();
        map.put("img", icno[i]);
        map.put("text",name[i]);
        dataList.add(map);
    }
}

} ```

GridView主佈局檔案activity_main.xml

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:background="#000" tools:context="com.example.l7.MainActivity" > <GridView android:id="@+id/gridview" android:layout_width="match_parent" android:layout_height="wrap_content" android:columnWidth="80dp" android:stretchMode="spacingWidthUniform" android:numColumns="3" /> </LinearLayout>

列表項佈局gridview_item.xml

```xml

<ImageView
    android:id="@+id/img"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_marginTop="10dp" 
    android:src="@drawable/ic_launcher" />
<TextView
    android:id="@+id/text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="2dp" 
    android:layout_gravity="center"
    android:textColor="#FFF"
    android:text="文字"
    />

```

效果圖

這裡寫圖片描述

gridview的android:stretchMode

stretchMode 可選值: columnWidth 如果列有空閒空間就加寬列 spacingWidth 如果列有空閒空間就加寬各列間距 none 沒有任何動作 spacingWidthUniform 平均分配空間 上圖使用spacingWidthUniform

none效果

這裡寫圖片描述

columnWidth效果

這裡寫圖片描述

spacingWidth效果

這裡寫圖片描述