这是我的布局:
<?xml version="1.0" encoding="utf-8"?><!-- Style Theme.Transparent -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayoutVideo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:weightSum="1"
android:focusable="true"
android:clickable="true">
<VideoView
android:id="@+id/videoView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.75"
android:clickable="true"
android:focusable="true" />
</LinearLayout>
我将onclicklistener设置为父视图和子视图:
linearLayout.setOnClickListener(myOnlyhandler);
videoView.setOnClickListener(myOnlyhandler);
我只获得视频观看的点击事件。 我想要的是知道用户是否点击进入视频视图或外部(父)并执行不同的操作。我该如何得到这种行为?
由于 塔塔
答案 0 :(得分:9)
前段时间我实现了一个提供此类功能的Activity
基类。您只需注册一个自定义OnTouchOutsideViewListener
,一旦用户在安装了监听器后触摸您的视图,该自定义setOnTouchOutsideViewListener
就会收到通知。只需在您的活动实例上调用class YourActivity extends Activity {
private View mTouchOutsideView;
private OnTouchOutsideViewListener mOnTouchOutsideViewListener;
/**
* Sets a listener that is being notified when the user has tapped outside a given view. To remove the listener,
* call {@link #removeOnTouchOutsideViewListener()}.
* <p/>
* This is useful in scenarios where a view is in edit mode and when the user taps outside the edit mode shall be
* stopped.
*
* @param view
* @param onTouchOutsideViewListener
*/
public void setOnTouchOutsideViewListener(View view, OnTouchOutsideViewListener onTouchOutsideViewListener) {
mTouchOutsideView = view;
mOnTouchOutsideViewListener = onTouchOutsideViewListener;
}
public OnTouchOutsideViewListener getOnTouchOutsideViewListener() {
return mOnTouchOutsideViewListener;
}
@Override
public boolean dispatchTouchEvent(final MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
// Notify touch outside listener if user tapped outside a given view
if (mOnTouchOutsideViewListener != null && mTouchOutsideView != null
&& mTouchOutsideView.getVisibility() == View.VISIBLE) {
Rect viewRect = new Rect();
mTouchOutsideView.getGlobalVisibleRect(viewRect);
if (!viewRect.contains((int) ev.getRawX(), (int) ev.getRawY())) {
mOnTouchOutsideViewListener.onTouchOutside(mTouchOutsideView, ev);
}
}
}
return super.dispatchTouchEvent(ev);
}
/**
* Interface definition for a callback to be invoked when a touch event has occurred outside a formerly specified
* view. See {@link #setOnTouchOutsideViewListener(View, OnTouchOutsideViewListener).}
*/
public interface OnTouchOutsideViewListener {
/**
* Called when a touch event has occurred outside a given view.
*
* @param view The view that has not been touched.
* @param event The MotionEvent object containing full information about the event.
*/
public void onTouchOutside(View view, MotionEvent event);
}
}
即可。
您可以将此代码粘贴到现有的活动类中,也可以创建一个可以在整个项目中重复使用的基本活动类。
{{1}}