How to add action bar to a DialogFragment?

早过忘川 提交于 2019-12-06 15:35:33
Lan

As Up ActionBar action on DialogFragment indicates: There is no way to attach an ActionBar to the DialogFragment even though you can set the theme of the DialogFragment it will not register as a ActionBar to it, Dialog.getActionBar() will always return null.

But there's always the cases that I really want to use DialogFragment(which contain ActionBar like style) instead of Activity. Just add a Layout that will look like an ActionBar into the DialogFragment's Layout

the following is the steps: 1) DialogFragment layout: about_dialog.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white" >

<include android:id="@+id/fake_action_bar"
    layout="@layout/fake_action_bar_with_backbotton" />

2) Implement a ActionBar like layout: fake_action_bar_with_backbotton.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/fake_action_bar"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"
    app:navigationIcon="@drawable/ic_menu_back"
    android:background="@color/background_material_dark"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

Note: the @drawable/ic_menu_back is copied from sdk\platforms\android-21\data\res\drawable-hdpi

3) Update the DialogFragment code

public class AboutDialogFragment extends DialogFragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // use Theme_Holo_Light for full screen
        // use Theme_Holo_Dialog for not full screen
        // first parameter: DialogFragment.STYLE_NO_TITLE   no title
        setStyle(DialogFragment.STYLE_NO_FRAME, android.R.style.Theme_Holo_Light_DarkActionBar);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.about_dialog, container, false);

        // set the listener for Navigation
        Toolbar actionBar = (Toolbar) v.findViewById(R.id.fake_action_bar);
        if (actionBar!=null) {
            final AboutDialogFragment window = this;
            actionBar.setTitle(R.string.about_title);
            actionBar.setNavigationOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    window.dismiss();
                }
            });
        }
        return v;
    }
}

Wish it can help!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!