gallery(画廊)用来展示图片集合,将图片放入数据源中,传到适配器里。然后绑定视图。
xml文件:(width写成wrap_content的话,每次只显示一张图片)
<Gallery
android:id="@+id/gallery"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
main:
Gallery gallery = (Gallery) findViewById(R.id.gallery);//找到对象id
final int[] images = {R.drawable.blue001,R.drawable.blue002,R.drawable.blue003,
R.drawable.blue004,R.drawable.blue005,R.drawable.blue006,
R.drawable.blue007,R.drawable.blue008};//将图片放入数组中
适配器,
BaseAdapter mAdapter = new BaseAdapter() {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView iv = new ImageView(MainActivity.this);
iv.setImageResource(images[position]);//设置图片资源
iv.setScaleType(ScaleType.FIT_XY);//设置填充方式
iv.setLayoutParams(new Gallery.LayoutParams(500, 600));//布局
return iv;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public int getCount() {
return images.length;
}
};
gallery.setSpacing(60);//设置每个图片间距
gallery.setAnimationDuration(100);<span style="white-space:pre"> </span>
gallery.setGravity(Gravity.CENTER);//设置居中对齐
gallery.setAdapter(mAdapter);
gallery.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(), ""+position, 0).show();
}
});
效果图下