Android控件之GridView

网格视图GridView的排列方式与矩阵类似,当屏幕上有很多元素(文字、图片或其他元素)需要按矩阵格式进行显示时,就可以使用GridView控件来实现。

看到目前为止就是用适配器进行规定布局方式,并把每个布局文件(imageview 和 textview)显示出来。


布局文件xml:

<RelativeLayout 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"
     >
  
	   <ImageView 
	        android:id="@+id/itemImage1"
	        android:layout_width="40dp"
	        android:layout_height="40dp"
	        android:scaleType="fitCenter"
	        android:layout_centerHorizontal="true" />
	   <TextView 
	    android:id="@+id/itemName1"
	    android:layout_height="wrap_content"
	    android:layout_width="wrap_content"
	    android:layout_below="@+id/itemImage1"
	    android:layout_centerHorizontal="true"    
	    />
      
</RelativeLayout>




GridView的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"
     >

    <GridView 
        android:id="@+id/gridView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:numColumns="3"
        android:horizontalSpacing="10dp"
        android:verticalSpacing="10dp"
        ></GridView>   

</LinearLayout>

numColumns属性指示图片展示多少列


Main:
package com.example.grilview;

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

import android.app.Activity;
import android.os.Bundle;
import android.widget.GridView;
import android.widget.SimpleAdapter;

public class GrilView01 extends Activity {

	//声明一个GridView	
	private GridView gridview;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gril_view01);
		
		// 获得控件
		gridview = (GridView)findViewById(R.id.gridView1);
		
		
		// 得到数据
		String [] ImageName = {"book","camera","computer","connecton","driving","fitting","home",
								"music","newspaper","pacman","phone","video","watch"};
		int [] ImageId={
				R.drawable.book,R.drawable.camera,R.drawable.computer,R.drawable.connection,R.drawable.driving,
				R.drawable.fitting,R.drawable.home,R.drawable.music,R.drawable.newspaper,R.drawable.pacman,
				R.drawable.phone,R.drawable.video,R.drawable.watch
		};
		
		
		ArrayList<HashMap<String, Object>> array=new ArrayList<HashMap<String,Object>>();
		
		for(int i=0;i<ImageName.length;i++)
		{
			HashMap<String, Object> map= new HashMap<String, Object>();
			map.put("ImageName", ImageName[i]);
			map.put("ImageId", ImageId[i]);
			array.add(map);
		}
		
		// 适配器定义规则
		SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(), array,R.layout.image, new String[]{"ImageName","ImageId"}, new int[]{R.id.itemName1,R.id.itemImage1});
		// 绑定适配器
		gridview.setAdapter(adapter);
		
		
	}
}


效果:

Android控件之GridView_第1张图片



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