Android 开发:ViewFlipper 左右滑动效果
fmms
13年前
怎么实现Android主页面的左右拖动效果。其实实现起来很简单,就是使用ViewFlipper来将您要来回拖动的View装在一起,然后与GestureDetector手势识别类来联动,确定要显示哪个View,加上一点点动画效果即可。 <pre class="brush:java; toolbar: true; auto-links: false;">public class TestFlip extends Activity implements OnGestureListener { private ViewFlipper flipper; private GestureDetector detector; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); detector = new GestureDetector(this); flipper = (ViewFlipper) this.findViewById(R.id.ViewFlipper01); flipper.addView(addView(R.layout.layout1)); flipper.addView(addView(R.layout.layout2)); flipper.addView(addView(R.layout.layout3)); flipper.addView(addView(R.layout.layout4)); } private View addView(int layout) { LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(layout, null); return view; } @Override public boolean onTouchEvent(MotionEvent event) { return this.detector.onTouchEvent(event); } @Override public boolean onDown(MotionEvent e) { // TODO Auto-generated method stub return false; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (e1.getX() - e2.getX() > 120) { this.flipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_left_in)); this.flipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.push_left_out)); this.flipper.showNext(); return true; } else if (e1.getX() - e2.getX() < -120) { this.flipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_right_in)); this.flipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.push_right_out)); this.flipper.showPrevious(); return true; } return false; } @Override public void onLongPress(MotionEvent e) { // TODO Auto-generated method stub } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // TODO Auto-generated method stub return false; } @Override public void onShowPress(MotionEvent e) { // TODO Auto-generated method stub } @Override public boolean onSingleTapUp(MotionEvent e) { // TODO Auto-generated method stub return false; } } </pre> <pre class="brush:xml; toolbar: true; auto-links: false;"><?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android" Android:orientation="vertical" Android:layout_width="fill_parent" Android:layout_height="fill_parent" > <ViewFlipper Android:id="@+id/ViewFlipper01" Android:layout_width="fill_parent" android:layout_height="fill_parent"> </ViewFlipper> </LinearLayout> </pre>