您的位置:首页 > 其它

OnTouchListener的使用

2015-10-24 15:39 197 查看
此篇文章重点在于修改onTouchListener的方法,来响应手指在手机屏幕上滑动,比如手指往上,往下,往左,往右滑动时,屏幕的背景颜色会改变。

此方法也是我在拆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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: