循环浏览图片的另一种方法—Gallery组件的使用

来源:互联网 发布:弯矩图绘制软件 编辑:程序博客网 时间:2024/05/22 02:14

我们实现图片的滑动一般使用ViewPager来实现,于是我想尝试看有没有其他方法,经过一番查找,发现有这么一个组件Gallery也能实现这一效果,并且通过修改adapter能循环滚动播放图片。

一、创建布局文件activity_main

<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"
    tools:context=".MainActivity" >
<Gallery 
   android:id="@+id/gallery"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_marginTop="30dp"
   />
</LinearLayout>

二、添加一些属性 values/attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="Gallery">
                <attr name="android:galleryItemBackground" />
    </declare-styleable>
</resources>

三、代码实现

public class MainActivity extends Activity {
int[] myImageIds={R.drawable.and1,R.drawable.and10,
R.drawable.and11,R.drawable.and12,
R.drawable.and3,R.drawable.and6,
R.drawable.and7,R.drawable.and8};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Gallery gallery=(Gallery) findViewById(R.id.gallery);
ImageAdapter adapter=new ImageAdapter(this);
gallery.setAdapter(adapter);
gallery.setOnItemClickListener(new OnItemClickListener() {


@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this,
"第"+gallery.getItemAtPosition(position)+"张图片",
Toast.LENGTH_SHORT).show();

}
});
}

}

四、创建适配器

public class ImageAdapter extends BaseAdapter{
int mGalleryItemBackground;
Context context;

public ImageAdapter(Context context) {
super();
this.context = context;
TypedArray typedArray=obtainStyledAttributes(R.styleable.Gallery);
mGalleryItemBackground=typedArray.getResourceId(R.styleable.Gallery_android_galleryItemBackground, 0);
typedArray.recycle();
}
@Override
public int getCount() {
return Integer.MAX_VALUE;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView=new ImageView(context);
imageView.setImageResource(myImageIds[position%myImageIds.length]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(300,400));//添加gallery的布局属性
imageView.setBackgroundResource(mGalleryItemBackground);//设置背景
return imageView;
}

}


效果图如下,点击下一张图片会显示在正中间,并且循环浏览:


0 0