ImageSwitcher使用示例
mainActivity如下:
package c.c;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.view.animation.AnimationUtils;import android.widget.ImageSwitcher;import android.widget.ImageView;import android.widget.ViewSwitcher.ViewFactory;public class MainActivity extends Activity { private ImageSwitcher mImageSwitcher; private int images []; private int imageIndex=0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } private void init(){ images=new int[]{R.drawable.a,R.drawable.b,R.drawable.c,R.drawable.d}; mImageSwitcher=(ImageSwitcher) findViewById(R.id.imageSwitcher); //设置用于显示图片的ImageView mImageSwitcher.setFactory(new ViewFactory() {public View makeView() {ImageView imageView=new ImageView(MainActivity.this);return imageView;} }); //处理点击事件 mImageSwitcher.setOnClickListener(new ClickListenerImpl()); //设置图片进入和退出动画 mImageSwitcher.setInAnimation (AnimationUtils.loadAnimation(MainActivity.this, android.R.anim.slide_in_left)); mImageSwitcher.setOutAnimation (AnimationUtils.loadAnimation(MainActivity.this, android.R.anim.slide_in_left)); //设置初始时显示的图片 mImageSwitcher.setImageResource(images[imageIndex]); }private class ClickListenerImpl implements OnClickListener {public void onClick(View v) {imageIndex++;if (imageIndex == images.length) {imageIndex = 0;}mImageSwitcher.setImageResource(images[imageIndex]);}}}
main.xml如下:
<RelativeLayout 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" > <ImageSwitcher android:id="@+id/imageSwitcher" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" /></RelativeLayout>