自定義Dialog點選彈框外的區域無法關閉問題
阿新 • • 發佈:2019-01-01
最近在實現一個自定義Dialog時,產品要求點選彈框外的區域要能夠關閉Dialog,本來以為很簡單的,只需加一行程式碼:
setCanceledOnTouchOutside(true);
就解決了嘛,結果呢,不!管!用!
好吧,既然出了問題,那就找找原因吧。
自定義Dialog的佈局檔案很簡單,就包括一個ListView和一個取消按鈕,程式碼如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width ="match_parent"
android:layout_height="wrap_content"
android:id="@+id/dialog_root"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="@+id/cancel"
android:layout_width="match_parent"
android:layout_height ="54dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="10dp"
android:layout_marginTop="8dp"
android:background="@drawable/cancel_selector"
android:gravity="center"
android:text="@string/cancel"
android:textColor="@color/btn_bg"
android:textSize="18dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/cancel"
android:background="@drawable/listview_bg">
<ListView
android:id="@+id/dialog_listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:cacheColorHint="@color/transparent"
android:divider="@color/live_disable"
android:dividerHeight="1px"
android:fadingEdge="none"
android:listSelector="@drawable/transparent"
android:scrollbars="none"/>
</LinearLayout>
</RelativeLayout>
既然點選Dialog區域外無反應,那麼就要看看,點選的部分是不是確實不屬於Dialog呢?
首先,在AndroidStudio工具欄裡找到Android Device Monitor(如下圖裡的小機器人圖示),點選開啟。
然後,選中自己的程式程序,點選Dump View按鈕(如下圖所示icon)
這時候在右側就能看到Dialog的佈局層級檢視,我出現問題的dialog佈局檢視如下:
可以看到,紅色框框就是Dialog的根佈局,也就是說灰色透明區域仍然屬於Dialog本身。而setCanceledOnTouchOutside(true)這個方法是指點選Dialog之外的螢幕區域才有效,問題就出在這兒了。
找到問題的原因,解決辦法就簡單了,只需要在程式碼裡找到Dialog的根佈局,然後設定點選事件,關閉Dialog就可以啦。
findViewById(R.id.dialog_root).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
dismiss();
}
});
四不四很簡單來,希望可以幫助有需要的同學~~~