android自动画廊,一个简单的Android画廊实例

本文详细介绍了如何在Android中使用Gallery组件展示图片,并自定义ImageAdapter进行图片加载。通过设置监听器,实现点击图片显示位置的功能。同时,通过调整ImageView的参数,实现了图片的缩放和布局大小的设定。
摘要由CSDN通过智能技术生成

[android]代码库public class GalleryDemo extends Activity {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main); /* 透过findViewById取得 */

Gallery g = (Gallery) findViewById(R.id.mygallery); /* 新增一ImageAdapter并设定给Gallery对象 */

g.setAdapter(new ImageAdapter(this)); /* 设定一个itemclickListener并Toast被点选图片的位置 */

g.setOnItemClickListener(new OnItemClickListener() {

public void onItemClick(AdapterView parent, View v, int position,

long id) {

Toast.makeText(

GalleryDemo.this,

getString(R.string.my_gallery_text_pre) + position

+ getString(R.string.my_gallery_text_post),

Toast.LENGTH_SHORT).show();

}

});

} /* 改写BaseAdapter自定义一ImageAdapter class */

public class ImageAdapter extends BaseAdapter { /* 宣告变量 */

int mGalleryItemBackground;

private Context mContext; /* ImageAdapter的建构子 */

public ImageAdapter(Context c) {

mContext = c; /* 使用在res/values/attrs.xml中的定义 * 的Gallery属性. */

TypedArray a = obtainStyledAttributes(R.styleable.Gallery); /*

* 取得Gallery属性的Index

* id

*/

mGalleryItemBackground = a.getResourceId(

R.styleable.Gallery_android_galleryItemBackground, 0); /* 让对象的styleable属性能够反复使用 */

a.recycle();

} /* 一定要重写的方法getCount,传回图片数目 */

public int getCount() {

return myImageIds.length;

} /* 一定要重写的方法getItem,传回position */

public Object getItem(int position) {

return position;

} /* 一定要重写的方法getItemId,传回position */

public long getItemId(int position) {

return position;

} /* 一定要重写的方法getView,传回一View对象 */

public View getView(int position, View convertView, ViewGroup parent) { /* 产生ImageView对象 */

ImageView i = new ImageView(mContext); /* 设定图片给imageView对象 */

i.setImageResource(myImageIds[position]); /* 重新设定图片的宽高 */

i.setScaleType(ImageView.ScaleType.FIT_XY); /* 重新设定Layout的宽高 */

i.setLayoutParams(new Gallery.LayoutParams(136, 88)); /* 设定Gallery背景图 */

i.setBackgroundResource(mGalleryItemBackground); /* 传回imageView物件 */

return i;

} /* 建构一Integer array并取得预加载Drawable的图片id */

private Integer[] myImageIds = { R.drawable.photo1, R.drawable.photo2,

R.drawable.photo3, R.drawable.photo4, R.drawable.photo5,

R.drawable.photo6, };

}

}

694748ed64b9390909c0d88230893790.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值