xml文件
activity-main.xml
<ViewFlipper xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/viewFlipper" android:layout_width="match_parent" android:layout_height="match_parent"> <include android:id="@+id/view1" layout="@layout/view1"></include> <include android:id="@+id/view2" layout="@layout/view2"></include> <include android:id="@+id/view3" layout="@layout/view3"></include> <include android:id="@+id/view4" layout="@layout/view4"></include> <include android:id="@+id/view5" layout="@layout/view5"></include> </ViewFlipper>
view1.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" android:background="@drawable/android01"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/view1" android:textSize="30sp" android:layout_gravity="center_horizontal"/> </LinearLayout>
MainActivity
package com.viewflipperdemo; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.animation.AnimationUtils; import android.widget.ViewFlipper; public class MainActivity extends Activity implements View.OnTouchListener{ private ViewFlipper viewFlipper; private float mTouchDownX;//手指按下的X坐标 private float mTouchUpX;//手指松开时的X坐标 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); viewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper); /*viewFlipper.setAutoStart(true); viewFlipper.setFlipInterval(2000);*/ viewFlipper.setOnTouchListener(this); } @Override public boolean onTouch(View v, MotionEvent event) { //当手指在屏幕上按下时 if (event.getAction() == MotionEvent.ACTION_DOWN) { mTouchDownX = event.getX(); //取得左右滑动时,取得X的坐标 Log.i("Temp", "mTouchDownX:" + mTouchDownX); return true; } else if (event.getAction() == MotionEvent.ACTION_UP) { mTouchUpX = event.getX(); Log.i("Temp", "mTouchUpX:" + mTouchUpX); //从左到右时 if (mTouchUpX - mTouchDownX>100) { //设置动画 viewFlipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_right_in)); viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.push_right_out)); viewFlipper.showPrevious(); } else if(mTouchDownX- mTouchUpX>100) {//从右到左时 viewFlipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_left_in)); viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.push_left_out)); viewFlipper.showNext(); } return true; } return false; } }
自己总结:
ViewFlipper用于页面翻页,--》 ViewAnimator ---->FrameLayout 所有可以翻页
XML