Android控件之GridView

转自http://www.cnblogs.com/linjiqin/archive/2011/02/23/1962535.html

Android控件之GridView探究

GridView是一项显示二维的viewgroup,可滚动的网格。一般用来显示多张图片。

以下模拟九宫图的实现,当鼠标点击图片时会进行相应的跳转链接。

目录结构

main.xml布局文件,存放GridView控件

复制代码
<?xml version="1.0" encoding="utf-8"?>
<!--
android:numColumns="auto_fit" ,GridView的列数设置为自动
android:columnWidth="90dp",每列的宽度,也就是Item的宽度
android:stretchMode="columnWidth",缩放与列宽大小同步
android:verticalSpacing="10dp",两行之间的边距,如:行一(NO.0~NO.2)与行二(NO.3~NO.5)间距为10dp
android:horizontalSpacing="10dp",两列之间的边距
-->
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:columnWidth="90dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
复制代码

night_item.xml布局文件,存放显示控件

复制代码
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:paddingBottom="4dip"
android:layout_width="fill_parent">
<ImageView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_centerHorizontal="true"
android:id="@+id/itemImage" >
</ImageView>
<TextView android:layout_width="wrap_content"
android:layout_below="@+id/itemImage"
android:layout_height="wrap_content"
android:text="TextView01"
android:layout_centerHorizontal="true"
android:id="@+id/itemText">
</TextView>
</RelativeLayout>
复制代码

strings.xml

复制代码
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, GvActivity!</string>
<string name="app_name">九宫图</string>
<string name="test_name1">跳转到TestActivity1</string>
<string name="test_name2">跳转到TestActivity2</string>
<string name="test_name3">跳转到TestActivity3</string>
</resources>
复制代码

清单文件

复制代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ljq.gv"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".GvActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".TestActivity1" android:label="@string/test_name1"/>
<activity android:name=".TestActivity2" android:label="@string/test_name2"/>
<activity android:name=".TestActivity3" android:label="@string/test_name3"/>
</application>
<uses-sdk android:minSdkVersion="7" />

</manifest>
复制代码

跳转类TestActivity1、TestActivity2、TestActivity3

复制代码
package com.ljq.gv;

import android.app.Activity;
import android.os.Bundle;

public class TestActivity1 extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
}
}

package com.ljq.gv;

import android.app.Activity;
import android.os.Bundle;

public class TestActivity2 extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
}
}

package com.ljq.gv;

import android.app.Activity;
import android.os.Bundle;

public class TestActivity3 extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
}
}
复制代码

类GvActivity

复制代码
package com.ljq.gv;

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

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class GvActivity extends Activity {
private String texts[] = null;
private int images[] = null;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

images=new int[]{R.drawable.p1, R.drawable.p2,
R.drawable.p3, R.drawable.p4,
R.drawable.p5,R.drawable.p6,
R.drawable.p7,R.drawable.p8};
texts = new String[]{ "宫式布局1", "宫式布局2",
"宫式布局3", "宫式布局4",
"宫式布局5", "宫式布局6",
"宫式布局7", "宫式布局8"};

GridView gridview = (GridView) findViewById(R.id.gridview);
ArrayList<HashMap<String, Object>> lstImageItem = new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < 8; i++) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("itemImage", images[i]);
map.put("itemText", texts[i]);
lstImageItem.add(map);
}

SimpleAdapter saImageItems = new SimpleAdapter(this,
lstImageItem,// 数据源
R.layout.night_item,// 显示布局
new String[] { "itemImage", "itemText" },
new int[] { R.id.itemImage, R.id.itemText });
gridview.setAdapter(saImageItems);
gridview.setOnItemClickListener(new ItemClickListener());
}

class ItemClickListener implements OnItemClickListener {
/**
* 点击项时触发事件
*
* @param parent 发生点击动作的AdapterView
* @param view 在AdapterView中被点击的视图(它是由adapter提供的一个视图)。
* @param position 视图在adapter中的位置。
* @param rowid 被点击元素的行id。
*/
public void onItemClick(AdapterView<?> parent, View view, int position, long rowid) {
HashMap<String, Object> item = (HashMap<String, Object>) parent.getItemAtPosition(position);
//获取数据源的属性值
String itemText=(String)item.get("itemText");
Object object=item.get("itemImage");
Toast.makeText(GvActivity.this, itemText, Toast.LENGTH_LONG).show();

//根据图片进行相应的跳转
switch (images[position]) {
case R.drawable.p1:
startActivity(new Intent(GvActivity.this, TestActivity1.class));//启动另一个Activity
finish();//结束此Activity,可回收
break;
case R.drawable.p2:
startActivity(new Intent(GvActivity.this, TestActivity2.class));
finish();
break;
case R.drawable.p3:
startActivity(new Intent(GvActivity.this, TestActivity3.class));
finish();
break;
}

}
}
}
复制代码

运行结果

 

 

GridView实现一行显示并左右滚动

使用GridView达到Gallery效果

 

 

[html] view plaincopy
 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!-- res/layout/gridview_to_gallery.xml -->  
  3. <HorizontalScrollView  xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="wrap_content"  
  6.     android:scrollbars="none">  
  7.         <LinearLayout   
  8.             android:layout_width="fill_parent"  
  9.             android:layout_height="fill_parent"   
  10.             android:orientation="horizontal">  
  11.             <GridView android:id="@+id/grid"  
  12.                 android:layout_width="1300dp"  
  13.                 android:layout_height="fill_parent"  
  14.                 android:gravity="center"  
  15.                 android:columnWidth="100dip"  
  16.                 android:horizontalSpacing="10dip"  
  17.                 android:verticalSpacing="10dip"/>  
  18.         </LinearLayout>  
  19. </HorizontalScrollView>  

 

[java] view plaincopy
 
  1. public class GridViewDemo extends Activity {  
  2.     @Override  
  3.     public void onCreate(Bundle savedInstanceState) {  
  4.         super.onCreate(savedInstanceState);  
  5.         setContentView(R.layout.gridview_to_gallery);  
  6.           
  7.         GridView gridview = (GridView) findViewById(R.id.grid);  
  8.         ImageAdapter adapter = new ImageAdapter(this);//一个继承BaseAdapter的自定义适配器  
  9.         adapter.setImages(getImages());  
  10.         gridview.setAdapter(adapter);  
  11.         gridview.setNumColumns(adapter.getCount());  
  12.   
  13.         gridview.setOnItemClickListener(new OnItemClickListener() {  
  14.             @Override  
  15.             public void onItemClick(AdapterView<?> av, View v, int position, long id) {  
  16.                 Toast.makeText(GridViewDemo.this, "" + position, Toast.LENGTH_SHORT).show();  
  17.             }  
  18.         });  
  19.     }  
  20.     /** 
  21.      * 取出SD卡中的图片(也可改为取网络或数据库图片) 
  22.      * @return 
  23.      */  
  24.     private List<Bitmap> getImages() {  
  25.         List<Bitmap> list = new ArrayList<Bitmap>();  
  26.         for (int i=1; i<=12; i++) {  
  27.             String imagePath = "/sdcard/image_0"+i+".jpg";  
  28.             if (i >= 10) imagePath = "/sdcard/image_"+i+".jpg";  
  29.             list.add(BitmapFactory.decodeFile(imagePath));  
  30.         }  
  31.         return list;  
  32.     }  
  33. }  


 

自定义适配器

[java] view plaincopy
 
    1. public class ImageAdapter extends BaseAdapter {  
    2.     private Context mContext;  
    3.     private List<Bitmap> images = new ArrayList<Bitmap>();  
    4.   
    5.     public ImageAdapter(Context c) {  
    6.         mContext = c;  
    7.     }  
    8.   
    9.     public List<Bitmap> getImages() {  
    10.         return images;  
    11.     }  
    12.     public void setImages(List<Bitmap> images) {  
    13.         this.images = images;  
    14.     }  
    15.   
    16.     public int getCount() {  
    17.         return images.size();  
    18.     }  
    19.   
    20.     public Object getItem(int position) {  
    21.         return images.get(position);  
    22.     }  
    23.   
    24.     public long getItemId(int position) {  
    25.         return 0;  
    26.     }  
    27.   
    28.     // create a new ImageView for each item referenced by the Adapter  
    29.     public View getView(int position, View convertView, ViewGroup parent) {  
    30.         ImageView imageView;  
    31.         if (convertView == null) {  // if it's not recycled, initialize some attributes  
    32.             imageView = new ImageView(mContext);  
    33.             imageView.setLayoutParams(new GridView.LayoutParams(85, 85));  
    34.             imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);  
    35.             imageView.setPadding(8, 8, 8, 8);  
    36.         } else {  
    37.             imageView = (ImageView) convertView;  
    38.         }  
    39.   
    40.         imageView.setImageBitmap(images.get(position));  
    41.         return imageView;  
    42.     }  
    43. }  

posted on 2015-05-17 20:05  wwicked  阅读(194)  评论(0编辑  收藏  举报

导航