一種方法是增加一個透明的空View
(讓我們給它那覆蓋在佈局的一切,除了爲,你想成爲hidable查看標識overlayView
)(讓我們給該ID bashful
):
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!--
All your existing non-bashful Views must be here, *before* overlayView.
That gives them a lower Z-order than overlayView.
-->
<View
android:id="@+id/overlayView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<!-- The bashful View must come last, so that it has the highest Z-order. -->
<View
android:id="@+id/bashful"
...
/>
</RelativeLayout>
然後,在View.OnTouchListener
(NOT View.OnClickListener
)爲overlayView
,你可以這樣做:
@Override
public boolean onTouch(View v, MotionEvent event) {
mBashfulView.setVisibility(View.GONE);
}
此代碼假定你有一個mBashfulView
變量引用bashful
查看。
僅當用戶觸摸bashful
視圖以外的任何地方時纔會調用偵聽器。
「我嘗試添加一個oncliecllistner的相對佈局,但沒有工作。」 - 請發佈你的代碼,並解釋什麼不工作。 – Egor
將onClickListener添加到您的RelativeLayout以隱藏您的自定義視圖。這會點擊您的自定義視圖以隱藏它,因此只需將onClickListener添加到您的自定義視圖中即可攔截點擊事件。 – Gudin
@Gudin如果我在自定義視圖上添加聽衆,如何知道何時在自定義視圖外點按以隱藏它? – spenf10