OnTouchListener的使用
2015-10-24 15:39
197 查看
此篇文章重点在于修改onTouchListener的方法,来响应手指在手机屏幕上滑动,比如手指往上,往下,往左,往右滑动时,屏幕的背景颜色会改变。
此方法也是我在拆2048的游戏代码时学会的,很有意思。
我们先在xml中自定义一个组件
然后回到layout.java中:
其中主类继承Linearlayout,通过setBackgroundColor方法来修改背景的颜色;
在我们点击屏幕的时候,我们就可以通过getX(),getY()方法来获取坐标,通过坐标的比较来判断往哪个方向滑动
源码下载:
http://download.csdn.net/detail/cuicanxingchen123456/9209361
此方法也是我在拆2048的游戏代码时学会的,很有意思。
我们先在xml中自定义一个组件
<com.example.layout android:id="@+id/lay" android:layout_width="fill_parent" android:layout_height="200dp" android:background="#00FF00" android:orientation="horizontal" > </com.example.layout>
然后回到layout.java中:
public class layout extends LinearLayout{ float x,y,XX,YY; public layout(Context context) { super(context); // TODO Auto-generated constructor stub init(); } public layout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub init(); } public layout(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub init(); } @SuppressLint("ClickableViewAccessibility") public void init(){ setOrientation(LinearLayout.HORIZONTAL); // setBackgroundColor(0xffffff); setOnTouchListener(new View.OnTouchListener(){ @SuppressLint({ "ResourceAsColor", "ClickableViewAccessibility" }) @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub switch(event.getAction()){ case MotionEvent.ACTION_DOWN: x=event.getX(); y=event.getY(); System.out.println("DOWN_X:"+x+",DOWN_Y"+y); break; case MotionEvent.ACTION_UP: XX=event.getX(); YY=event.getY(); System.out.println("UP_XX:"+XX+",UP_YY"+YY); if(Math.abs(XX)>Math.abs(YY)){ if((XX-x)<-5){ System.out.println("向左滑"); setBackgroundColor(R.color.blue); }else{ System.out.println("向右滑"); setBackgroundColor(R.color.aliceblue); } }else{ if((XX-x)<-5){ System.out.println("向上滑"); setBackgroundColor(R.color.black); }else{ System.out.println("向下滑"); setBackgroundColor(R.color.darkcyan); } } break; } return true; } } ); } }
其中主类继承Linearlayout,通过setBackgroundColor方法来修改背景的颜色;
在我们点击屏幕的时候,我们就可以通过getX(),getY()方法来获取坐标,通过坐标的比较来判断往哪个方向滑动
源码下载:
http://download.csdn.net/detail/cuicanxingchen123456/9209361
相关文章推荐
- Java一步一脚—ArrayList使用
- 动态语言与静态语言
- 【IT修真院】零基础到就业一个月系列之【CSS】篇
- hadoop_入门1
- 贪婪算法--去掉 n 位正整数中的 s 位
- [No00002E]关于大数据,你不知道的6个迷思
- 使用mybatis生成相关文件时java.sql.SQLException: Access denied for user 'root'@'localhost' (using password)
- Lua和C语言的交互详解
- 对象之间的关系
- oracle 表查询二
- [Maven]How do I tell Maven to use the latest version of a dependency?
- 【数竞】完全是出于兴趣
- 第八周项目3顺序串算法
- 数组
- Java web之Tomcat下域名绑定IP
- Java WebService 简单实例
- 关于“重复”的一段交流
- oracle 表查询一
- 《STL源码剖析》迭代器以及Traits设计
- Excel导出