Up ActionBar action on DialogFragment

Saad Farooq picture Saad Farooq · Jun 10, 2014 · Viewed 10.8k times · Source

I have a DialogFragment that is styled to full screen using setStyle(STYLE_NORMAL, R.style.Theme_App).

The DialogFragment shows fine but the up action (the homeAsUp action on the ActionBar) does not work. I tried implementing onOptionsItemSelected in the DialogFragment but it is never called.

Is there a way to get the up action callback in the DialogFragment so I can dismiss it ? For reference, I'm using ActionBarCompat.

Answer

Sheraz Ahmad Khilji picture Sheraz Ahmad Khilji · Oct 12, 2015

This wasn't possible but there is a workaround for this using aToolbar. Now you can include Toolbar as part of your DialogFragment layout xml and can set its design/icon according to your needs. You will also need to implement setNavigationOnClickListener if you want the back button to behave like it does normally. See the sample class below.

package com.package.name;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;



public class MyDialogFragment extends DialogFragment {
    private View parentView;
    private Toolbar toolbar;


    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        setStyle(DialogFragment.STYLE_NO_FRAME, R.style.Theme_AppCompat_NoActionBar);
        return super.onCreateDialog(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //The layout xml file contains the toolbar
        parentView = inflater.inflate(R.layout.dialogfragment_createpost, container, false);
        initView();
        initData();
        return parentView;
    }


    private void initView() {
        toolbar = (Toolbar) parentView.findViewById(R.id.toolbar);

    }

    private void initData() {
        toolbar.setTitle("Post");
        //Set naviagtion icon to back button drawable
        toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
// handle back button naviagtion
                dismiss();
            }
        });
    }
}