Android编程实现左右滑动切换背景的方法
本文实例讲述了Android编程实现左右滑动切换背景的方法。分享给大家供大家参考,具体如下:
最近想做一个左右滑动切换背景图片的应用,特地将自己的研究分享一下:
这个需要继承2个监听接口OnGestureListener, OnTouchListener
关于这2个接口大家可以在网上查一下
同时需要设置2个属性
bgLayout.setOnTouchListener(this); bgLayout.setLongClickable(true);
并且在这个函数中有如下这几句话
publicbooleanonTouch(Viewv,MotionEventevent){ //TODOAuto-generatedmethodstub returnthis.mGesture.onTouchEvent(event); }
附送代码:
publicclassSwitcherActivityextendsActivityimplementsOnGestureListener, OnTouchListener{ /**Calledwhentheactivityisfirstcreated.*/ LinearLayoutbgLayout=null; privateGestureDetectormGesture=null; privateintflag=3; @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); mGesture=newGestureDetector(this); bgLayout=(LinearLayout)findViewById(R.id.bg); bgLayout.setBackgroundResource(R.drawable.bg3); bgLayout.setOnTouchListener(this); bgLayout.setLongClickable(true); } publicbooleanonDown(MotionEvente){ //TODOAuto-generatedmethodstub returnfalse; } publicbooleanonFling(MotionEvente1,MotionEvente2,floatvelocityX, floatvelocityY){ //处理左右滑动 if(e1.getX()-e2.getX()>100){//向左滑动 if(flag==3){ bgLayout.setBackgroundResource(R.drawable.bg4); flag=4; returntrue; } if(flag==4){ bgLayout.setBackgroundResource(R.drawable.bg5); flag=5; returntrue; } if(flag==1){ bgLayout.setBackgroundResource(R.drawable.bg2); flag=2; returntrue; } if(flag==2){ bgLayout.setBackgroundResource(R.drawable.bg3); flag=3; returntrue; } }elseif(e1.getX()-e2.getX()<-100){//向右滑动 if(flag==3){ bgLayout.setBackgroundResource(R.drawable.bg2); flag=2; returntrue; } if(flag==2){ bgLayout.setBackgroundResource(R.drawable.bg1); flag=1; returntrue; } if(flag==5){ bgLayout.setBackgroundResource(R.drawable.bg4); flag=4; returntrue; } if(flag==4){ bgLayout.setBackgroundResource(R.drawable.bg3); flag=3; returntrue; } } returnfalse; } publicvoidonLongPress(MotionEvente){ //TODOAuto-generatedmethodstub } publicbooleanonScroll(MotionEvente1,MotionEvente2,floatdistanceX, floatdistanceY){ //TODOAuto-generatedmethodstub returnfalse; } publicvoidonShowPress(MotionEvente){ //TODOAuto-generatedmethodstub } publicbooleanonSingleTapUp(MotionEvente){ //TODOAuto-generatedmethodstub returnfalse; } publicbooleanonTouch(Viewv,MotionEventevent){ //TODOAuto-generatedmethodstub returnthis.mGesture.onTouchEvent(event); } }
更多关于Android图片与特效相关内容感兴趣的读者可查看本站专题:《Android开发动画技巧汇总》和《Android图形与图像处理技巧总结》
希望本文所述对大家Android程序设计有所帮助。