您的位置:首页 > 其它

使用ImageSwitcher+Graller实现简单的幻灯式图片浏览器

2015-12-18 00:00 274 查看
摘要: 使用ImageSwitcher+Graller实现简单的幻灯式图片浏览器。
Grallery-画廊视图,能够按水平方向显示内容。并且可用手指直接拖动图片的移动,一般用来浏览图片,被选中的选项位于中间,并且可以响应事件显示信息。
ImageSwitcher是一个图像切换器。

实现效果如图:





布局文件中只需要一个拖切换器和画廊视图显示列表图片.

<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"
android:orientation="vertical" >

<ImageSwitcher
android:id="@+id/image_switcher"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingTop="30px" />

<Gallery
android:id="@+id/gallery"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="30px"
android:spacing="5px" />

</LinearLayout>


ImageSwitcher:

ImageSwitcher imageSwitcher = (ImageSwitcher)findViewById(R.id.image_switcher);

设置ViewFactory接口:

// 设置ViewFactory接口
imageSwitcher.setFactory(new ViewFactory() {
@Override
public View makeView() {
ImageView iv = new ImageView(MainActivity.this);
iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
iv.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
return iv;
}
});

设置图片切换器的动画效果

imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in)); // 设置淡入效果
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out)); // 设置淡出效果


Grallery-画廊视图

Gallery gallery = (Gallery)findViewById(R.id.gallery);

设置Grallery关联的适配器:

gallery.setAdapter(new BaseAdapter() {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if(convertView == null){
imageView = new ImageView(MainActivity.this);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(180,135));
TypedArray typedArray = obtainStyledAttributes(R.styleable.Gallery);
imageView.setBackgroundResource(typedArray.getResourceId(R.styleable.Gallery_android_galleryItemBackground, 0));
imageView.setPadding(5, 0, 5, 0);
}else {
imageView = (ImageView)convertView;
}
imageView.setImageResource(imageld[position]); // imageld 是一个int[]{} 里面包含了所显示的图片ID => private int imageld[] = new int[] { R.drawable.img01, R.drawable.img02.....}
return imageView;
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public Object getItem(int position) {
return position;
}

@Override
public int getCount() {
return imageld.length;
}
});

设置监听事件:

gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int postion, long arg3) {
imageSwitcher.setImageResource(imageld[postion]); // 根据图片索引获取图片ID,并设置给ImageSwitcher
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: