基于对慕课网教程的笔记
Gallery
xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Gallery
android:id="@+id/gallery"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
实例化控件与添加适配器
gallery = (Gallery) findViewById(R.id.gallery);
is=(ImageSwitcher) findViewById(R.id.is);
// gallery加载适配器
adapter = new ImageAdapter(res, this);
gallery.setAdapter(adapter);
自定义适配器
要使图片无限循环 所以要返回 Integer.MAX_VALUE (最大值)
//返回数据源的数量
@Override
public int getCount() {
// TODO Auto-generated method stub
return Integer.MAX_VALUE;
}
相对应的 在 getview中setBackgroundResource的参数不再设置为position
image.setBackgroundResource(res[position%res.length]);
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Log.i("Main", "position="+position+"res的角标="+position%res.length);
ImageView image=new ImageView(context);
image.setBackgroundResource(res[position%res.length]);
image.setLayoutParams(new Gallery.LayoutParams(200, 150));
image.setScaleType(ScaleType.FIT_XY);
return image;
}
其中 image.setLayoutParams(new Gallery.LayoutParams(200, 150));设置图片的大小
android:scaleType是控制图片如何 resized/moved来匹对ImageView的size FIT_XY / fitXY 把图片 不按比例 扩大/缩小到View的大小显示
ImageSwitch
imageswitch可以在图片显示和切换的时候加载动画效果,imageswitch中加载的其实就是一个个imageview
xml布局
<ImageSwitcher
android:id="@+id/is"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ImageSwitcher>
首先添加接口implements ViewFactory
给gallery添加监听事件 实现滑到的图片显示在imageswitch中
is.setFactory(this);
is=(ImageSwitcher) findViewById(R.id.is);
获得当前显示的图片
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
//image.setBackgroundResource(res[position%res.length]);
is.setBackgroundResource(res[position%res.length]);
实现接口中的makeview方法public View makeView() {
// TODO Auto-generated method stub
ImageView image=new ImageView(this);
image.setScaleType(ScaleType.FIT_CENTER);
return image;
}
添加动画效果is.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
is.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
//image.setBackgroundResource(res[position%res.length]);
is.setBackgroundResource(res[position%res.length]);
public View makeView() {
// TODO Auto-generated method stub
ImageView image=new ImageView(this);
image.setScaleType(ScaleType.FIT_CENTER);
return image;
}
is.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
is.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));