Can't get transparent DialogFragment

后端 未结 3 675
走了就别回头了
走了就别回头了 2020-12-29 14:35

I have a dialog Fragment which look like that.

\"enter

AlertDialog ad          


        
3条回答
  •  春和景丽
    2020-12-29 15:02

    The issue is in default dialog theme. Based on this and this answers it's much easier to achieve your target.

    The Activity should be like the following:

    public class MyActivity extends FragmentActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            getWindow().requestFeature(Window.FEATURE_NO_TITLE);
            setContentView(R.layout.main);
        }
    
        @Override
        public void onBackPressed() {
            MyDialogFragment.newInstance("title title").show(getSupportFragmentManager(), "dialog");
        }
    }
    

    And fragment:

    public class MyDialogFragment extends android.support.v4.app.DialogFragment {
    
        /**
         * Create a new instance of MyDialogFragment, providing "title"
         * as an argument.
         */
        static MyDialogFragment newInstance(String title) {
            MyDialogFragment frag = new MyDialogFragment();
            Bundle args = new Bundle();
    
            args.putString("title", title);
            frag.setArguments(args);
            return frag;
        }
    
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            Dialog dialog = new Dialog(getActivity(),android.R.style.Theme_Translucent_NoTitleBar);
            final View view = getActivity().getLayoutInflater().inflate(R.layout.share_or_die, null);
    
            final Drawable d = new ColorDrawable(Color.BLACK);
            d.setAlpha(130);
    
            dialog.getWindow().setBackgroundDrawable(d);
            dialog.getWindow().setContentView(view);
    
            final WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
            params.width = WindowManager.LayoutParams.WRAP_CONTENT;
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            params.gravity = Gravity.CENTER;
    
            dialog.setCanceledOnTouchOutside(true);
    
            return dialog;
        }
    }
    

    Also, be sure to do the following: before setContentView() in the activity, getWindow().requestFeature(Window.FEATURE_NO_TITLE) should be added in order to use *NoTitleBar style.

    The result is (I've used LinearLayout with single TextView inside): enter image description here

提交回复
热议问题