Android 控件GridView的使用

java测试代码:

package com.example.gridview;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity {

	private ArrayList<HashMap<String, Object>> data;
	private String[] iconName = { "通讯录", "日历", "照相机", "时钟", "游戏", "短信", "铃声", "设置", "语音", "天气", "浏览器", "视频" };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		data = new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < iconName.length; i++) {

			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("image", R.drawable.ic_launcher);
			map.put("icon", iconName[i]);

			data.add(map);
		}
		GridView mGridView = (GridView) findViewById(R.id.gridview);
		
		String[] from = { "image", "icon" };

		int[] resource = { R.id.image, R.id.text };
		mGridView.setAdapter(new SimpleAdapter(this, data, R.layout.item, from, resource));

	}

}

需要的activity_main.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"
    tools:context="com.example.gridview.MainActivity" >

    <!-- numColumns列数设置为自动 
    	columnWidth每列的宽度,也就是Item的宽度
    	stretchMode缩放与列宽大小同步
    -->

    <GridView
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:columnWidth="80dp"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth" >
    </GridView>

</LinearLayout>

需要的item.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"
    android:padding="10dp"
    android:gravity="center"
    tools:context="com.example.gridview.MainActivity" >

  <ImageView 
      android:id="@+id/image"
      android:layout_width="60dp"
      android:layout_height="60dp"
      android:src="@drawable/ic_launcher"/>
  
  <TextView 
      android:id="@+id/text"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginTop="5dp"
      android:text="文字"/>

</LinearLayout>


你可能感兴趣的:(Android 控件GridView的使用)