有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法使我的DialogFragment背景透明

我创建了一个定制的DialogFragment,就像《开发者指南》中描述的那样。 现在我试图做的事情听起来很简单,但我无法让它工作。 我在我的布局xml中定义了:安卓:background="@安卓:color/transparent",我是这样加载的(在我的onCreateDialog中):

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

LayoutInflater inflater = getActivity().getLayoutInflater();
    
final View view = inflater.inflate(R.layout.pausedialog, null);
setStyle(STYLE_NO_FRAME, R.style.CustomDialog);

正如您所见,我还尝试在DialogFragment中设置自定义样式,其定义如下:

<style name="CustomDialog" parent="安卓:style/Theme.Dialog">
    <item name="安卓:windowBackground">@null</item>
    <item name="安卓:windowNoTitle">true</item>
    <item name="安卓:windowIsFloating">true</item>
    <item name="安卓:windowIsTranslucent">true</item> 
    <item name="安卓:alwaysDrawnWithCache">false</item>
    <item name="安卓:windowContentOverlay">@null</item>
</style>

我也试过getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(0)); 这会导致空指针异常

我正在使用安卓.support.v4.app.DialogFragment。这是原因吗? 还是我做错了什么


共 (2) 个答案

  1. # 1 楼答案

    这对我有用。我创造了一种新的风格:

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

    然后在我的DialogFragment的onCreate()方法中设置这个样式,如下所示:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.CustomDialog);
    }
    
  2. # 2 楼答案

    尝试在dialogFragment类实现的onCreate方法中设置样式和主题

    @Override
        public void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
             int style=DialogFragment.STYLE_NO_TITLE;
             int theme=android.R.style.Theme_Translucent;
             setStyle(style, theme);
        }
    

    或者

    如果您使用的是Dialog类,那么还可以在Dialog实例上设置样式和主题