使用Gallery制作图片浏览器
MainActivity.class
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener,ViewSwitcher.ViewFactory { private Gallery gallery; private ImageSwitcher imageSwitcher; //数据源 private int[] res = {R.drawable.item1,R.drawable.item2,R.drawable.item3,R.drawable.item4, R.drawable.item5,R.drawable.item6, R.drawable.item7,R.drawable.item8, R.drawable.item9,R.drawable.item10,R.drawable.item11,R.drawable.item12}; private ImageAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gallery = (Gallery) findViewById(R.id.gallery); imageSwitcher = (ImageSwitcher) findViewById(R.id.imageswitch); adapter = new ImageAdapter(res,this); gallery.setAdapter(adapter); gallery.setOnItemSelectedListener(this); //imageSwitcher加载工厂factory imageSwitcher.setFactory(this); imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in)); imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_out)); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { imageSwitcher.setBackgroundResource(res[position % res.length]); } @Override public View makeView() { ImageView image = new ImageView(this); //等比例 居中缩放 image.setScaleType(ImageView.ScaleType.CENTER.FIT_CENTER); return image; }
ImageAdapter类 自己写的Adapter 继承于BaseAdapter
ImageAdapter.class
public class ImageAdapter extends BaseAdapter { private int[] res; private Context context; public ImageAdapter(int[] res,Context context){ this.res = res; this.context = context; } //获取数量 @Override public int getCount() { return res.length; // return Integer.MAX_VALUE; 约等于无限数量 } //获取项目 @Override public Object getItem(int position) { return res[position]; } //获取在适配器中的位置 @Override public long getItemId(int position) { return position; } //获取单个的View @Override public View getView(int position, View convertView, ViewGroup parent) { //new出一个新的View ImageView image = new ImageView(context); //给ImageView加载对应的图像资源 image.setBackgroundResource(res[position]); //利用取余 无限图片位置 不受数目限制了 res[position % res.length] //设置view在Gallery中缩略图的大小 image.setLayoutParams(new Gallery.LayoutParams(200,150)); //设置缩放模式 image.setScaleType(ImageView.ScaleType.FIT_XY); return image; } }
Activity.xml
<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" tools:context=".MainActivity"> <Gallery android:id="@+id/gallery" android:layout_width="match_parent" android:layout_height="wrap_content"/> <ImageSwitcher android:layout_gravity="center_vertical" android:layout_below="@id/gallery" android:id="@+id/imageswitch" android:layout_width="match_parent" android:layout_height="wrap_content"> </ImageSwitcher> </LinearLayout>