一、mainactivity.java
package com.example.text;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
public class tupian extends Activity {
/** Called when the activity is first created. */
private Gallery gallery;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.img);
//初始化Gallery。
gallery=(Gallery)findViewById(R.id.gallery);
try {
//设置Gallery的Adapter。
gallery.setAdapter(new ImageAdapter
(tupian.this));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//点击事件。
gallery.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int itemid,
long arg3) {
// TODO Auto-generated method stub
setTitle("您点击了第"+String.valueOf(itemid+1)+"项");
}});}
}
二、ImageAdapter.java
package com.example.text;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
//定义Context,即Activity
private Context context;
//定义整型数组 即图片源。
private Integer image[]={R.drawable.item1,R.drawable.gc,
R.drawable.gg
};
public ImageAdapter(Context c) throws IllegalArgumentException, IllegalAccessException
{
context=c;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
//获取图片个数。
return image.length;
}
@Override
public Object getItem(int position){
// TODO Auto-generated method stub
//获取图片在库中的位置。
return position;
}
@Override
public long getItemId(int position){
// TODO Auto-generated method stub
//获取图片在库中的位置。
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageview=new ImageView(context);
//给imageView设置图片资源。
imageview.setImageResource(image[position%image.length]);
//设置比例类型。
imageview.setScaleType(ImageView.ScaleType.FIT_XY);
//设置图片布局和显示大小。
imageview.setLayoutParams(new Gallery.LayoutParams(200,200));
//设置图片之间的距离。
imageview.setPadding(30,0,30,0);
return imageview;
}
}
///*gallery不循环显示图片:
//定义整型数组:图片源。
private Integer image[]={R.drawable.item1,R.drawable.gc, R.drawable.gg };
public int getCount() {
// TODO Auto-generated method stub
//获取图片个数。
return image.length; //不循环
//return Integer.Max_Value; 循环
}