Удалить черный фон в пользовательском диалоге

Я хочу удалить черный фон в пользовательском диалоге, как показано на рисунке. Я уверен, что черный фон был из диалога, а не из фона приложения.

пользовательский диалог с черным фоном вокруг него;

Код AlertDialog

public class MyAlertDialog extends AlertDialog { 
    public MyAlertDialog(Context context) 
    {  
        super(context); 
    }  

    public MyAlertDialog(Context context, int theme) 
    { super(context, theme); }
}

Код активности

public void showMyDialogOK(Context context, String s, DialogInterface.OnClickListener OkListener) {        
    MyAlertDialog myDialog = new MyAlertDialog(context, R.style.MyDialog2);        
    myDialog.setTitle(null); 
    myDialog.setMessage(s);        
    myDialog.setButton(DialogInterface.BUTTON_POSITIVE ,"Ok", OkListener);
    myDialog.show();    
}

Стили

<?xml version="1.0" encoding="utf-8"?>
    <resources>
        <style name="MyTheme" parent="@android:style/Theme.NoTitleBar.Fullscreen">
            <item name="android:alertDialogStyle">@style/AlertDialog</item>  
        </style>    

        <style name="MyTheme2" parent="@android:style/Theme.Black">
            <item name="android:alertDialogStyle">@style/AlertDialog</item>    
        </style> 

        <style name="AlertDialog">        
            <item name="android:fullDark">@null</item>
            <item name="android:fullBright">@null</item>
            <item name="android:topDark">@drawable/popup_top_dark</item>
            <item name="android:topBright">@null</item>
            <item name="android:centerBright">@null</item>
            <item name="android:centerDark">@drawable/popup_center_dark</item>
            <item name="android:centerMedium">@null</item>
            <item name="android:bottomDark">@null</item>
            <item name="android:bottomBright">@null</item>
            <item name="android:bottomMedium">@drawable/popup_bottom_medium</item>
        </style>

        <style name="MyDialog2" parent="@android:Theme.Dialog">        
            <item name="android:windowBackground">@null</item>    
            <item name="android:buttonStyle">@style/CustomButton</item>  
        </style>    

        <style name="CustomButton" parent="@android:style/Widget.Button">        
            <item name="android:background">@drawable/button_stateful</item>  
        </style>
</resources>

Имиджевые ресурсы

popup_center_dark.9.png

popup_center_dark.9.png

popup_bottom_medium.9.png

popup_bottom_medium.9.png

popup_top_dark.9.png

popup_top_dark.9.png

16 ответов

Решение
public MyAlertDialog(Context context, int theme) extends AlertDialog { 
        super(context, theme);
        getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
    }

Sonehow getWindow().setBackgroundDrawable() не работал для меня с AlertDialog, Я нашел более простое решение с помощью диалога. Вот мой код -

        final Dialog dialog = new Dialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        dialog.setContentView(R.layout.popup_window);
        dialog.show();

Попробуй это:

myDialog.getWindow().clearFlags(LayoutParams.FLAG_DIM_BEHIND);

После того, как я попробовал множество других решений этой проблемы, у меня получилось:

<style name="translucentDialog" parent="android:Theme.Holo.Dialog">
    <item name="android:windowBackground">@android:color/transparent</item>
</style>

А затем настройте мой диалог, чтобы использовать эту тему.

Удалите цвет непрозрачности фона, вам просто нужно установить DimAmount

dialog.getWindow().setDimAmount(float amount);

Новое значение затемнения: от 0 для отсутствия затемнения до 1 для полного затемнения.

Используйте две строки кода ниже. Также протестирован.

getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

// стиль кода в style.xml:

<style name="translucentDialog" parent="android:Theme.Holo.Dialog">
    <item name="android:windowBackground">@android:color/transparent</item>
</style>

// в действии: установить стиль для диалога:

   Dialog dialogconf = new Dialog(TreeAct.this, R.style.translucentDialog);
            dialogconf.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
                   dialogconf.setContentView(R.layout.dialog_layout);

У меня работал следующий метод:

getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

Просто поменяйте диалог родителя им.

С черным фоном

<style name="MyDialog2" parent="@android:Theme.Dialog">        

Без черного фона

<style name="MyDialog2" parent="@android:style/Theme.DeviceDefault.Light.Dialog">

Вы можете создать макет XML, как показано ниже, и установить этот макет в диалоговом окне (dialog.xml):

<?xml version="1.0" encoding="utf-8"?>
<ScrollView android:id="@+id/ScrollView01"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android" style="@style/white_background_bl_aatharv">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:scrollbars="vertical"
        android:scrollbarAlwaysDrawVerticalTrack="true" android:id="@+id/instructions_view">

        <TextView android:id="@+id/TextView01" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:textColor="#FFFFFF"
            android:text="text here " />
    </LinearLayout>
</ScrollView>

Вот код для установки макета в диалоговом окне предупреждения:

AlertDialog alert = cndtnsbuilder.create();
                        alert.setView(LayoutInflater.from(
                                currentactivity.this).inflate(
                                R.layout.dialog, null));
                        alert.show();

Чтобы удалить цвет фона, на макете вам просто нужно установить фон @null

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@null">

Это работает для меня.bottomSheetDialogFragment

          override fun onStart() {
    super.onStart()
    // remove black outer overlay, or change opacity
    dialog?.window?.also { window ->
        window.attributes?.also { attributes ->
            attributes.dimAmount = 0.1f
            window.attributes = attributes
        }
    }
}

У меня была та же проблема с моим настраиваемым диалоговым окном, основанным на Alertdialog.Builder, у которого был черный фон, отображаемый в заголовке и теле при использовании:

builder.setView(rootView)
  .setTitle(dialog_title)
  .setMessage(dialog_mesg)

Решение было 1- Используйте одну из предопределенных тем строителя диалога оповещения:

  • THEME_DEVICE_DEFAULT_DARK
  • THEME_DEVICE_DEFAULT_LIGHT
  • THEME_HOLO_DARK
  • THEME_HOLO_LIGHT THEME_TRADITIONAL

THEME_DEVICE_DEFAULT_LIGHT работал лучше всего для меня

2 - установить цвета кнопки диалога по умолчанию (положительный / отрицательный), на какой цвет вы хотите, например, так:

 Button b = mAlertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
 Button d = mAlertDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
 b.setTextColor(ContextCompat.getColor(getActivity(), R.color.primary));
 d.setTextColor(ContextCompat.getColor(getActivity(), R.color.primary));

проверьте ниже сообщение в блоге для более подробной информации и хитростей к темам: http://blog.supenta.com/2014/07/02/how-to-style-alertdialogs-like-a-pro/

проверено на Oreo 8.1

В KOTLIN примените это к объекту диалогового окна предупреждения

      window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
 dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

Я удалил черный фон моего настраиваемого диалога кодом после alertDialog.show():

try {
    ViewGroup viewGroup1 = (ViewGroup) dialogView.getParent();
    if (viewGroup1 != null) {
            viewGroup1.setBackgroundResource(android.R.color.transparent);

        ViewGroup viewGroup2 = (ViewGroup) viewGroup1.getParent();
            if (viewGroup2 != null) {
                     viewGroup2.setBackgroundResource(android.R.color.transparent);
            } 
    }
} catch (Exception e) {
}
Другие вопросы по тегам