ActionBar in a DialogFragment

Paul Blessing picture Paul Blessing · Jul 11, 2012 · Viewed 31.2k times · Source

In the Calendar app on my Galaxy Tab 10.1, when creating a new event a dialog comes up with Done and Cancel buttons in the title bar/action bar area.

enter image description here

I'd like to implement this in my app. I've tried using setHasOptionsMenu(true) in addition to overriding onCreateOptionsMenu in my DialogFragment subclass, but my action items do not appear. I've also tried calling getDialog().getActionBar() from within onCreateView but it always returns null.

I am able to get this working if I start an Activity rather than showing a dialog but that takes up the whole screen. Is there a standard way to do this using a DialogFragment?

Answer

StrikeForceZero picture StrikeForceZero · Sep 5, 2012

using the idea from a google group post I was able to pull it off styling an activity. you would want to modify the height and width to a "dynamic" size of your choice preferably. Then set whatever ActionBar buttons you would like

<style name="PopupTheme" parent="android:Theme.Holo.Light.Dialog">
    <item name="android:windowIsFloating">false</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowSoftInputMode">stateAlwaysHidden</item>
    <item name="android:windowActionModeOverlay">true</item>
    <item name="android:windowIsTranslucent">true</item>
</style>

--

public static void showAsPopup(Activity activity) {
    //To show activity as dialog and dim the background, you need to declare android:theme="@style/PopupTheme" on for the chosen activity on the manifest
    activity.requestWindowFeature(Window.FEATURE_ACTION_BAR);
    activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND,
            WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    LayoutParams params = activity.getWindow().getAttributes(); 
    params.height = 850; //fixed height
    params.width = 850; //fixed width
    params.alpha = 1.0f;
    params.dimAmount = 0.5f;
    activity.getWindow().setAttributes((android.view.WindowManager.LayoutParams) params); 
    setContentView(R.layout.activity_main);
}