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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.viewflipperdemo.MainActivity" > <ViewFlipper android:id="@+id/flipper" android:layout_width="match_parent" android:layout_height="wrap_content" ></ViewFlipper> </RelativeLayout>
main.java
package com.example.viewflipperdemo; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.ViewFlipper; /** * ViewFlipper: * 安卓系统自带的一个多页面管理控件,它可以实现子页面的自动切换 * 为ViewFlipper加入View: * (1)在layout布局文件静态导入子View * (2)动态导入:addView()方法 * *案例实现: *(1)利用ViewFlipper实现的图片轮播 *(2)支持手势滑动的ViewFlipper * */ public class MainActivity extends Activity { private ViewFlipper flipper; private int[] resId = {R.drawable.pic1,R.drawable.pic2,R.drawable.pic3,R.drawable.pic4}; private float startX; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); flipper = (ViewFlipper) findViewById(R.id.flipper); /** * (1)利用ViewFlipper实现的图片轮播 */ //动态导入的方式为Flipper加入子view for (int i = 0; i < resId.length; i++) { flipper.addView(getImageView(i)); } //为ViewFlipper去添加动画效果 flipper.setInAnimation(this,R.anim.left_in); flipper.setOutAnimation(this,R.anim.left_out); //设定ViewFlipper视图切换的时间 3s flipper.setFlipInterval(3000); //开始播放 flipper.startFlipping(); } @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub switch(event.getAction()){ //手指落下 case MotionEvent.ACTION_DOWN:{ startX = event.getX(); break; } //手指滑动 case MotionEvent.ACTION_MOVE:{ //向右滑动 if(event.getX()-startX>=100){ flipper.setInAnimation(this,R.anim.left_in);; flipper.setOutAnimation(this, R.anim.left_out); flipper.showPrevious(); } //向左滑动 if(startX-event.getX()>=100){ flipper.setInAnimation(this,R.anim.right_in);; flipper.setOutAnimation(this, R.anim.right_out); flipper.showNext(); } break; } //手指抬起 case MotionEvent.ACTION_UP:{ break; } } return super.onTouchEvent(event); } private View getImageView(int res){ ImageView image = new ImageView(this); image.setBackgroundResource(resId[res]); return image; } }
时间: 2024-11-05 23:36:08