黑马程序员技术交流社区
标题:
Android图片切换器
[打印本页]
作者:
老衲玩IT
时间:
2013-8-27 14:36
标题:
Android图片切换器
/*Gallary对象加载缩略图集,并显示
*为Gallary对象添加选项监听事件,当选中
*一项时,对应的回调函数Switcher对象的图片设置
*为图片资源中一张下标与Gallary选项下标相同的图片
*/
public class ImageSwitcher1 extends Activity implements
AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory {//实现viewFactory
//图片切换器的实例引用
private ImageSwitcher mSwitcher;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//设置屏幕无标题
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.image_switcher_1);
//找到layout中的控件
mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
mSwitcher.setFactory(this);
//设置图片切换动画
mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_in));
mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_out));
//相册控件
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
g.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView parent, View v, int position, long id) {
//设置一张下标与item选项position相同图片
mSwitcher.setImageResource(mImageIds[position]);
}
public void onNothingSelected(AdapterView parent) {
}
public View makeView() {
ImageView i = new ImageView(this);
i.setBackgroundColor(0xFF000000);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
return i;
}
//自定义图片适配器
public class ImageAdapter extends BaseAdapter {
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(mThumbIds[position]);
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
i.setBackgroundResource(R.drawable.picture_frame);
return i;
}
private Context mContext;
}
private Integer[] mThumbIds = {
R.drawable.sample_thumb_0, R.drawable.sample_thumb_1,
R.drawable.sample_thumb_2, R.drawable.sample_thumb_3,
R.drawable.sample_thumb_4, R.drawable.sample_thumb_5,
R.drawable.sample_thumb_6, R.drawable.sample_thumb_7};
private Integer[] mImageIds = {
R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2,
R.drawable.sample_3, R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7};
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2