一、前言:
首先要说的是,这个控件其实是已经过时了的,如果大家对过时的用起来不舒服或者不美观的话,在我的下一篇博客中会给大家带来另一种ViewPager控件的体验,不过Gallery控件在页面展示上的效果的是不如ViewPager的,比如说,在图片的衔接上,Gallery是属于那种拖泥带水的,而ViewPager是干净利落的,因此这也是我为什么说Gallery为什么在某些效果方面不如ViewPager。
二、效果图:
三、代码:
xml布局代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.zking.laci.android09.GalleryActivity">
<Gallery
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/gallery_image"
></Gallery>
</LinearLayout>
Java代码:
package com.zking.laci.android09;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
public class GalleryActivity extends AppCompatActivity {
private Gallery giv;
private int images[]={R.drawable.a1,R.drawable.a2,R.drawable.a3};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
giv = (Gallery) findViewById(R.id.gallery_image);
giv.setAdapter(new MyAdapter());
}
class MyAdapter extends BaseAdapter{
@Override
public int getCount() {
return images.length;
}
@Override
public Object getItem(int position) {
return images[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView iv=new ImageView(GalleryActivity.this);
//给图片设置宽高
Gallery.LayoutParams layoutParams=new Gallery.LayoutParams(500,500);
iv.setLayoutParams(layoutParams);
iv.setImageResource(images[position]);
return iv;
}
}
}