ViewFlipper左右滑动事件
新建一个继承Activity类的ViewFlipperActivity,并设置布局文件为:viewflipper.xml。
首先在布局文件中添加一个TextView,和一个ViewFlipper,并在ViewFlipper布局中添加2个LinearLayout,里面设置不同的背景颜色。
<?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" >
<TextView android:id="@+id/viewflipper_tv01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="@string/show_information" android:textSize="22sp" />
<ViewFlipper android:id="@+id/viewflipper_viewflipper" android:layout_width="match_parent" android:layout_height="match_parent" >
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FFFF0000" > </LinearLayout>
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FF0000FF" > </LinearLayout> </ViewFlipper>
</LinearLayout> |
而后在Activity代码中,获取ViewFlipper对象,并通过onTouchListener()处理ViewFlipper显示的界面。
package lyx.feng.simpletextdemo; ...... public class ViewFlipperActivity extends Activity implements OnTouchListener { private ViewFlipper viewFlipper = null; private TextView tv = null;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.viewflipper); this.viewFlipper = (ViewFlipper) super .findViewById(R.id.viewflipper_viewflipper); this.tv = (TextView) super.findViewById(R.id.viewflipper_tv01); this.viewFlipper.setOnTouchListener(this); this.viewFlipper.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in)); this.viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out)); }
@Override public boolean onTouch(View v, MotionEvent event) { int start = 0; int end = 0; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: start = (int) event.getX(); break; case MotionEvent.ACTION_UP: end = (int) event.getX(); if (start - end > 10) { this.viewFlipper.showNext(); this.tv.setText("next"); // Toast.makeText(this, "next", Toast.LENGTH_SHORT).show(); } if (start - end < 10) { this.viewFlipper.showPrevious(); this.tv.setText("previous"); // Toast.makeText(this, "previous", Toast.LENGTH_SHORT).show(); } break; } return true; } }
|