第一步:layout文件
<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"
tools:context="${relativePackage}.${activityClass}" >
<ViewFlipper
android:id="@+id/viewflipper"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ViewFlipper>
</RelativeLayout>
第二步:java文件
package com.example.testviewflipper;
import android.R.integer;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewFlipper;
public class MainActivity extends Activity {
ViewFlipper viewFlipper;
float startX = 0;
ImageView imageView1;
ImageView imageView2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewFlipper = (ViewFlipper) findViewById(R.id.viewflipper);
/**
* 数据源
*/
imageView1 = new ImageView(this);
imageView1.setBackgroundResource(R.drawable.pic1);
imageView2 = new ImageView(this);
imageView2.setBackgroundResource(R.drawable.pic2);
/**
* 添加子view
*/
viewFlipper.addView(imageView1);
viewFlipper.addView(imageView2);
/**
* 设置view切换的动画
*/
// viewFlipper.setInAnimation(inAnimation);
// viewFlipper.setOutAnimation(outAnimation);
/**
* 设置view切换的时间间隔
*/
viewFlipper.setFlipInterval(2000);
/**
* view开始切换
*/
viewFlipper.startFlipping();
/**
* 设置左右滑动事件以及点击事件
*/
viewFlipper.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = event.getX();
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
/**
* 点击事件
*/
if ((event.getX() - startX) == 0) {
if (imageView1 == viewFlipper.getCurrentView()) {
Toast.makeText(MainActivity.this, "您选择了第一张图片", 2000)
.show();
}
if (imageView2 == viewFlipper.getCurrentView()) {
Toast.makeText(MainActivity.this, "您选择了第二张图片", 2000)
.show();
}
}
/**
* 向右滑动
*/
if ((event.getX() - startX) > 100) {
viewFlipper.showNext();
}
/**
* 向左滑动
*/
if ((startX - event.getX()) > 100) {
viewFlipper.showPrevious();
}
break;
default:
break;
}
return true;
}
});
}
}
三:源码