布局文件:
<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" > <ImageSwitcher android:id="@+id/imageSwitcher1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="5dp" > </ImageSwitcher> <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:layout_marginTop="5dp" android:orientation="horizontal" > <!-- 前一个箭头 --> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="forward" > </Button> <!-- 下一个箭头 --> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="next" > </Button> </LinearLayout> </LinearLayout>
实现代码:
package com.leaf.android; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.ViewSwitcher.ViewFactory; public class Main extends Activity implements OnClickListener { private Button mButton1, mButton2; private ImageSwitcher mImageSwitcher; private int[] image = { R.drawable.car1, R.drawable.car2, R.drawable.car3, R.drawable.car4, R.drawable.car5 }; private int index = 0;//用于浏览图片的次序 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mImageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher1); mButton1 = (Button) findViewById(R.id.button1); mButton2 = (Button) findViewById(R.id.button2); mButton1.setOnClickListener(this); mButton2.setOnClickListener(this); mImageSwitcher.setFactory(new ViewFactory() { public View makeView() { ImageView mImageView = new ImageView(Main.this); mImageView.setBackgroundColor(Color.GREEN); return mImageView; } }); mImageSwitcher.setImageResource(image[index]); } public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.button1: if (index > 0) { index--; } else { index = image.length - 1; } mImageSwitcher.setImageResource(image[index]); break; case R.id.button2: if (index < image.length - 1) { index++; } else { index = 0; } mImageSwitcher.setImageResource(image[index]); break; } } }
效果: