Android中TouchDelegate的用法浅析

一般TouchDelegate是在View类中的。

View类中出现TouchDelegate的地方如下:

public class View implements Drawable.Callback, KeyEvent.Callback,
        AccessibilityEventSource {
// ...
    /**
     * The delegate to handle touch events that are physically in this view
     * but should be handled by another view.
     */
    private TouchDelegate mTouchDelegate = null;

// ...
    /**
     * Sets the TouchDelegate for this View.
     */
    public void setTouchDelegate(TouchDelegate delegate) {
        mTouchDelegate = delegate;
    }

    /**
     * Gets the TouchDelegate for this View.
     */
    public TouchDelegate getTouchDelegate() {
        return mTouchDelegate;
    }
// ...
    public boolean onTouchEvent(MotionEvent event) {
// ...
        if (mTouchDelegate != null) {
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
        }
// ...
}


// ...
}
先放在这里,下面我们看看TouchDelegate给我们的提示:

/**
 * Helper class to handle situations where you want a view to have a larger touch area than its
 * actual view bounds. The view whose touch area is changed is called the delegate view. This
 * class should be used by an ancestor of the delegate. To use a TouchDelegate, first create an
 * instance that specifies the bounds that should be mapped to the delegate and the delegate
 * view itself.
 *


 * The ancestor should then forward all of its touch events received in its
 * {@link android.view.View#onTouchEvent(MotionEvent)} to {@link #onTouchEvent(MotionEvent)}.
 *


 *

靠,一大段E文,让人头大,不过很简单。

我用一幅图来表示上面的含义:

Android中TouchDelegate的用法浅析_第1张图片

简单点说,就是一般我们只能Click这个View2的时候,View2才响应,但是我们想要Click这个View1的Bounds内,这个View2也要响应。

就是这么简单。。。


所以我们使用时候有:

        TouchDelegate td = new TouchDelegate(bounds,  view2);
        view1.setTouchDelegate(td);
这样就OK了。。。

So, easy~~

当然你还可以自己派生TouchDelegate类。。

这里帖出代码:

// TestActivity.java

public class TestActivity extends Activity {
	
	private LinearLayout mView1, mViewBounds;
	private Button mView2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.a_testactivity);
		
		mView1 = (LinearLayout) findViewById(R.id.view1);
		mViewBounds = (LinearLayout) findViewById(R.id.viewBounds);
		mView2 = (Button) findViewById(R.id.view2);
		
		int v1Top = mView1.getTop();
		int v1Bottom = mView1.getBottom();
		
		ViewGroup.LayoutParams lp1 = mView1.getLayoutParams();
		ViewGroup.LayoutParams lpBounds = mViewBounds.getLayoutParams();
		
		Rect bounds = new Rect();
		bounds.left = 0;
		bounds.top = (lpBounds.height - lp1.height)/2;
		bounds.right = bounds.left + lpBounds.width;
		bounds.bottom = bounds.top + lpBounds.height;
		int a=2;
		int b=a;
		
		TouchDelegate td = new TouchDelegate(bounds, mView2);
		mView1.setTouchDelegate(td);
	}
}
// a_testactivity.xml



    

        

            
        
    










你可能感兴趣的:(android)