效果图:
一、activity代码
package com.liudan.activity;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Gallery;
import com.liudan.adapter.GalleryAdapter;
public class GalleryActivity extends Activity {
private Gallery gallery ;
private List<Integer> galleryList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initData();
gallery = (Gallery)findViewById(R.id.gallery);
GalleryAdapter galleryAdapter = new GalleryAdapter(this,galleryList);
gallery.setAdapter(galleryAdapter);
//设置显示在屏幕中间的图片,默认是把第一张图片显示在屏幕中间,那么在屏幕的左边就是空白。
gallery.setSelection(galleryList.size()/2);
}
private void initData() {
galleryList = new ArrayList<Integer>();
for(int i=0;i<8;i++){
galleryList.add(R.drawable.icon);
}
}
}
二、adapter代码
package com.liudan.adapter;
import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
public class GalleryAdapter extends BaseAdapter {
private List<Integer> galleryList;
private Context context;
public GalleryAdapter(Context context,List<Integer> galleryList) {
this.galleryList = galleryList;
this.context = context;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return galleryList.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return galleryList.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if(convertView == null){
ImageView imageView = new ImageView(context);
imageView.setImageResource(galleryList.get(position));
view = imageView;
}else{
view = convertView;
}
// TODO Auto-generated method stub
return view;
}
}
三、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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Gallery android:id="@+id/gallery"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_centerHorizontal="true"
android:spacing="10dip"/>
</LinearLayout>