开发者

Dialog with custom view, setCanceledOnTouchOutside doesn't work

开发者 https://www.devze.com 2023-03-08 23:37 出处:网络
am开发者_运维技巧 using a Dialog with a custom view. That view\'s layout is 300dp x 300dp is size and centered on the screen. Now i want it to be dismissed when the user touches outside the dialog. I

am开发者_运维技巧 using a Dialog with a custom view. That view's layout is 300dp x 300dp is size and centered on the screen. Now i want it to be dismissed when the user touches outside the dialog. I thought: great! there is a function for this: setCanceledOnTouchOutside(boolean). But i has no effect. It simply doesn't work. I also tried to add an onTouchListener and listen for events that are outside the dialog, but those events doesn't seem to be captured by the listener :(

Any ideas why this doesn't work or how it could be done in another way?

Here is how i declare the Dialog:

mMenuDialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);
    mMenuDialog.setContentView(R.layout.menu_dialog);
    mMenuDialog.setCancelable(true);
    mMenuDialog.setCanceledOnTouchOutside(true);

and here is the declaration of the custom view

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="300dp" android:layout_height="300dp"
android:background="@drawable/menu_dialog_background"
android:orientation="vertical" android:layout_gravity="center"
android:id="@+id/dialog_root">
...
</LinearLayout>

and here is the used background:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<padding android:left="15dp" android:top="15dp" android:right="15dp"
    android:bottom="15dp" />
<solid android:color="#f0f0f0" />
<corners android:radius="15dip" />
</shape> 


It might be a tad late but for those who are still looking for the answer, here it is.

Apply a custom style to your dialog. In your style, include this:

<item name="android:windowIsFloating">true</item>

Otherwise the dialog will use full screen. Hence no outside area to click to cancel. This works for dialogs with custom content.

Example:

<style name="dialog_theme" parent="@android:style/Theme.Dialog">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_gravity">center</item>
</style>

Hope this helps.


i did solve it now by wrapping my custom dialog view layout with an additional LinearLayout and adding an onTouchListener to this wrapping LinearLayout. In that onTouchListener i checked if the click was inside or outside the dialog.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号