你的位置:首页 > 操作系统

[操作系统]Android ViewFlipper控件实例


使用ViewFlipper实现两张图片切换效果,废话不多说,直接上代码。

java源码:

package com.example.viewflipper;import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.view.MotionEvent;import android.widget.ViewFlipper;public class MainActivity extends Activity {  private ViewFlipper viewflipper;  private float startx,endx;  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    viewflipper=(ViewFlipper) findViewById(R.id.viewFlipper1);  }    public boolean onTouchEvent(MotionEvent event) {    // TODO 自动生成的方法存根    int action=event.getAction();    if(action==MotionEvent.ACTION_DOWN)    {      startx=event.getX();    }else if(action==MotionEvent.ACTION_UP){      endx=event.getX();      if(startx-endx>20){        viewflipper.setInAnimation(this,android.R.anim.fade_in);        viewflipper.setOutAnimation(this,android.R.anim.fade_out);        /*viewflipper.setInAnimation(this,R.layout.in_rightleft);        viewflipper.setOutAnimation(this,R.layout.out_rightleft);*/        viewflipper.showNext();      }else if(endx-startx>20){        /*viewflipper.setInAnimation(this,R.layout.in_leftright);        viewflipper.setOutAnimation(this,R.layout.out_leftright);*/        viewflipper.setInAnimation(this,android.R.anim.fade_in);        viewflipper.setOutAnimation(this,android.R.anim.fade_out);        viewflipper.showPrevious();      }    }    return super.onTouchEvent(event);  }  }

使用ViewFlipper控件布局:

<RelativeLayout "http://schemas.android.com/apk/res/android"  ="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=".MainActivity" >  <ViewFlipper    android:id="@+id/viewFlipper1"    android:layout_width="match_parent"    android:layout_height="match_parent"     >     <LinearLayout    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <ImageView      android:id="@+id/imageView1"      android:layout_width="match_parent"      android:layout_height="match_parent"      android:src="@drawable/item1"      android:scaleType="centerCrop" />  </LinearLayout>  <LinearLayout    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <ImageView      android:id="@+id/imageView2"      android:layout_width="match_parent"      android:layout_height="match_parent"      android:src="@drawable/item2"      android:scaleType="centerCrop" />  </LinearLayout>  </ViewFlipper></RelativeLayout>

运行ok。