編輯:關於Android編程
本文背景:前些天用到了之前寫的自定義圖片文字復合控件,在給他設置監聽時遇到了麻煩。雖然最後解決了問題,但發現在不重寫LinearLayout的onInterceptTouchEvent時,子ImageView、子TextView、父Linearlayout三者不同的屬性配置(android:clickable android:focuseable)會造成自定義控件onClick監聽失敗、或成功。復寫了父Linearlayout 的onInterceptTouchEvent時,監聽不受子圖片、子文字的屬性影響。為知其所以然,深入研究android的事件傳遞機制,記錄於此。
/**
* Pass the touch screen motion event down to the target view, or this
* view if it is the target.
*
* @param event The motion event to be dispatched.
* @return True if the event was handled by the view, false otherwise.
*/
public boolean dispatchTouchEvent(MotionEvent event) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(event, 0);
}
if (onFilterTouchEventForSecurity(event)) {
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
return true;
}
if (onTouchEvent(event)) {
return true;
}
}
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
}
return false;
}找到這個判斷: if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED if (onTouchEvent(event)) {
return true;
}onTouchEvent的源碼比較多,貼最重要的: if (!mHasPerformedLongPress) {
// This is a tap, so remove the longpress check
removeLongPressCallback();
// Only perform take click actions if we were in the pressed state
if (!focusTaken) {
// Use a Runnable and post this rather than calling
// performClick directly. This lets other visual state
// of the view update before click actions start.
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
if (!post(mPerformClick)) {
performClick();
}
}
}可以看到有個performClick(),它的源碼裡有這麼一句 li.mOnClickListener.onClick(this); public boolean performClick() {
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnClickListener != null) {
playSoundEffect(SoundEffectConstants.CLICK);
li.mOnClickListener.onClick(this);
return true;
}
return false;
}package org.yanzi.ui;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.Button;
public class TestButton extends Button {
private final static String tag = "yan";
public TestButton(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
Log.i(tag, "TestButton-onTouchEvent-ACTION_DOWN...");
break;
case MotionEvent.ACTION_UP:
Log.i(tag, "TestButton-onTouchEvent-ACTION_UP...");
break;
default:break;
}
return super.onTouchEvent(event);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
Log.i(tag, "TestButton-dispatchTouchEvent-ACTION_DOWN...");
break;
case MotionEvent.ACTION_UP:
Log.i(tag, "TestButton-dispatchTouchEvent-ACTION_UP...");
break;
default:break;
}
return super.dispatchTouchEvent(event);
}
}
testBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i(tag, "testBtn---onClick...");
}
});
testBtn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
Log.i(tag, "testBtn-onTouch-ACTION_DOWN...");
break;
case MotionEvent.ACTION_UP:
Log.i(tag, "testBtn-onTouch-ACTION_UP...");
break;
default:break;
}
return false;
}
});@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
// TODO Auto-generated method stub
switch(ev.getAction()){
case MotionEvent.ACTION_DOWN:
Log.i(tag, "MainActivity-dispatchTouchEvent-ACTION_DOWN...");
break;
case MotionEvent.ACTION_UP:
Log.i(tag, "MainActivity-dispatchTouchEvent-ACTION_UP...");
break;
default:break;
}
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
Log.i(tag, "MainActivity-onTouchEvent-ACTION_DOWN...");
break;
case MotionEvent.ACTION_UP:
Log.i(tag, "MainActivity-onTouchEvent-ACTION_UP...");
break;
default:break;
}
return super.onTouchEvent(event);
}testBtn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
Log.i(tag, "testBtn-onTouch-ACTION_DOWN...");
break;
case MotionEvent.ACTION_UP:
Log.i(tag, "testBtn-onTouch-ACTION_UP...");
break;
default:break;
}
return true;
}
}); public boolean dispatchTouchEvent(MotionEvent ev) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
// Handle an initial down.
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Throw away all previous state when starting a new touch gesture.
// The framework may have dropped the up or cancel event for the previous gesture
// due to an app switch, ANR, or some other state change.
cancelAndClearTouchTargets(ev);
resetTouchState();
}
// Check for interception.
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
} else {
// There are no touch targets and this action is not an initial down
// so this view group continues to intercept touches.
intercepted = true;
}
// Check for cancelation.
final boolean canceled = resetCancelNextUpFlag(this)
|| actionMasked == MotionEvent.ACTION_CANCEL;
// Update list of touch targets for pointer down, if needed.
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
TouchTarget newTouchTarget = null;
boolean alreadyDispatchedToNewTouchTarget = false;
if (!canceled && !intercepted) {
if (actionMasked == MotionEvent.ACTION_DOWN
|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
final int actionIndex = ev.getActionIndex(); // always 0 for down
final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
: TouchTarget.ALL_POINTER_IDS;
// Clean up earlier touch targets for this pointer id in case they
// have become out of sync.
removePointersFromTouchTargets(idBitsToAssign);
final int childrenCount = mChildrenCount;
if (childrenCount != 0) {
// Find a child that can receive the event.
// Scan children from front to back.
final View[] children = mChildren;
final float x = ev.getX(actionIndex);
final float y = ev.getY(actionIndex);
final boolean customOrder = isChildrenDrawingOrderEnabled();
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = customOrder ?
getChildDrawingOrder(childrenCount, i) : i;
final View child = children[childIndex];
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
continue;
}
newTouchTarget = getTouchTarget(child);
if (newTouchTarget != null) {
// Child is already receiving touch within its bounds.
// Give it the new pointer in addition to the ones it is handling.
newTouchTarget.pointerIdBits |= idBitsToAssign;
break;
}
resetCancelNextUpFlag(child);
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// Child wants to receive touch within its bounds.
mLastTouchDownTime = ev.getDownTime();
mLastTouchDownIndex = childIndex;
mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
}
}
}
if (newTouchTarget == null && mFirstTouchTarget != null) {
// Did not find a child to receive the event.
// Assign the pointer to the least recently added target.
newTouchTarget = mFirstTouchTarget;
while (newTouchTarget.next != null) {
newTouchTarget = newTouchTarget.next;
}
newTouchTarget.pointerIdBits |= idBitsToAssign;
}
}
}
// Dispatch to touch targets.
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
// Dispatch to touch targets, excluding the new touch target if we already
// dispatched to it. Cancel touch targets if necessary.
TouchTarget predecessor = null;
TouchTarget target = mFirstTouchTarget;
while (target != null) {
final TouchTarget next = target.next;
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
} else {
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
if (dispatchTransformedTouchEvent(ev, cancelChild,
target.child, target.pointerIdBits)) {
handled = true;
}
if (cancelChild) {
if (predecessor == null) {
mFirstTouchTarget = next;
} else {
predecessor.next = next;
}
target.recycle();
target = next;
continue;
}
}
predecessor = target;
target = next;
}
}
// Update list of touch targets for pointer up or cancel, if needed.
if (canceled
|| actionMasked == MotionEvent.ACTION_UP
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
resetTouchState();
} else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
final int actionIndex = ev.getActionIndex();
final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
removePointersFromTouchTargets(idBitsToRemove);
}
}
if (!handled && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
}
return handled;
} public boolean onInterceptTouchEvent(MotionEvent ev) {
return false;
}package org.yanzi.ui;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.LinearLayout;
public class TestLinearLayout extends LinearLayout{
private final static String tag = "yan";
public TestLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
// TODO Auto-generated method stub
switch(ev.getAction()){
case MotionEvent.ACTION_DOWN:
Log.i(tag, "TestLinearLayout-dispatchTouchEvent-ACTION_DOWN...");
break;
case MotionEvent.ACTION_UP:
Log.i(tag, "TestLinearLayout-dispatchTouchEvent-ACTION_UP...");
break;
default:break;
}
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
// TODO Auto-generated method stub
switch(ev.getAction()){
case MotionEvent.ACTION_DOWN:
Log.i(tag, "TestLinearLayout-onInterceptTouchEvent-ACTION_DOWN...");
break;
case MotionEvent.ACTION_UP:
Log.i(tag, "TestLinearLayout-onInterceptTouchEvent-ACTION_UP...");
break;
default:break;
}
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
Log.i(tag, "TestLinearLayout-onTouchEvent-ACTION_DOWN...");
break;
case MotionEvent.ACTION_UP:
Log.i(tag, "TestLinearLayout-onTouchEvent-ACTION_UP...");
break;
default:break;
}
return super.onTouchEvent(event);
}
}
布局文件改成:testLinelayout = (TestLinearLayout)findViewById(R.id.linearlayout_test);
testLinelayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
Log.i(tag, "testLinelayout-onTouch-ACTION_DOWN...");
break;
case MotionEvent.ACTION_UP:
Log.i(tag, "testLinelayout-onTouch-ACTION_UP...");
break;
default:break;
}
return false;
}
});
testLinelayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i(tag, "testLinelayout---onClick...");
}
});
Android仿百度谷歌搜索自動提示框AutoCompleteTextView簡單應用示例
本文實例講述了Android仿百度谷歌搜索自動提示框AutoCompleteTextView簡單應用。分享給大家供大家參考,具體如下:現在我們上網幾乎都會用百度或者谷歌搜
Android 性能優化 內存優化之How Android Managers Memory(一)
前言在學習Android內存性能優化時,發現需要對Android系統的內存概況得有個概況了解,便有了此篇文章。這篇文章僅僅介紹相關於內存的,即輔助理解 官方文檔 How
Android掃描本地音樂文件開發案例分享
一、前言本來覺得so easy,真是沒想到,還搞了老半天,搞的我大汗淋漓,要拍桌子摔鍵盤了。 本想實現的功能是: 通過網易雲音樂/百度音樂/QQ音樂/酷狗音樂中一個API
[Android] SQLite數據庫之增刪改查基礎操作
在編程中經常會遇到數據庫的操作,而Android系統內置了SQLite,它是一款輕型數據庫,遵守事務ACID的關系型數據庫管理系統,它占用的資源非常低,能夠支持Windo