效果: 点击按钮时,你将会看到你是点击到了按钮,但没有看到点击后应该出现的吐司,
一个按钮要被拦截,要知道它是运行到哪里在执行点击后的业务逻辑的;
而点击按钮时只有当鼠标抬起时才执行,因此:看下面代码
布局代码: 就是一个按钮
<?xml version="1.0" encoding="utf-8"?>
<test.pgl.com.test.MyViewGroup xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="test.pgl.com.test.MainActivity">
<Button
android:onClick="click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮" />
</test.pgl.com.test.MyViewGroup>
MainActivity 代码:
package test.pgl.com.test;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View view) {
Toast.makeText(this, "按钮被点击了", Toast.LENGTH_SHORT).show();
}
}
MyViewGroup代码:
package test.pgl.com.test;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.LinearLayout;
import android.widget.Toast;
/**
* Created by Administrator on 2017/5/28.
*/
public class MyViewGroup extends LinearLayout {
public MyViewGroup(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (ev.getAction()==MotionEvent.ACTION_UP)
return true;
else
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Toast.makeText(getContext(), "ViewGroup被点击了", Toast.LENGTH_SHORT).show();
return super.onTouchEvent(event);
}
}
按钮点击后的业务逻辑在MotionEvent.ACTION_UP里:
所以找到它,直接返回一个true就不会让它走原来的逻辑了