天天看點

android 按鈕 攔截了點選事件,攔截按鈕點選事件(InterceptButtonClickEvent)

效果: 點選按鈕時,你将會看到你是點選到了按鈕,但沒有看到點選後應該出現的吐司,

一個按鈕要被攔截,要知道它是運作到哪裡在執行點選後的業務邏輯的;

而點選按鈕時隻有當滑鼠擡起時才執行,是以:看下面代碼

布局代碼: 就是一個按鈕

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">

android:onClick="click"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="按鈕" />

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;

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就不會讓它走原來的邏輯了