android横向浏览图片,Android使用gallery和imageSwitch制作可左右循环滑动的图片浏览器...
时间: 2023-06-26 18:04:10 浏览: 121
android通信录源码
5星 · 资源好评率100%
在Android中,可以使用Gallery和ImageSwitcher来实现可左右循环滑动的图片浏览器。
首先,在布局文件中添加一个Gallery和一个ImageSwitcher:
```
<Gallery
android:id="@+id/gallery"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center_vertical" />
<ImageSwitcher
android:id="@+id/imageSwitcher"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/gallery" />
```
然后,在Java代码中,需要为Gallery设置一个Adapter,并为ImageSwitcher设置一个ViewFactory。代码如下:
```
public class MainActivity extends AppCompatActivity {
private Gallery mGallery;
private ImageSwitcher mImageSwitcher;
private int[] mImageIds = new int[]{R.drawable.image1, R.drawable.image2, R.drawable.image3};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGallery = (Gallery) findViewById(R.id.gallery);
mImageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher);
mGallery.setAdapter(new ImageAdapter(this));
mImageSwitcher.setFactory(new ViewFactory() {
@Override
public View makeView() {
ImageView imageView = new ImageView(MainActivity.this);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
return imageView;
}
});
mGallery.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mImageSwitcher.setImageResource(mImageIds[position % mImageIds.length]);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context context) {
mContext = context;
}
@Override
public int getCount() {
return Integer.MAX_VALUE;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new Gallery.LayoutParams(200, 200));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mImageIds[position % mImageIds.length]);
return imageView;
}
}
}
```
这里的关键是设置Gallery的Adapter为一个无限循环的Adapter,以及在Gallery的OnItemSelectedListener中更新ImageSwitcher的图片资源。同时,ImageAdapter负责为Gallery提供每个Item的View。
这样,我们就可以实现一个左右循环滑动的图片浏览器了。
阅读全文