dazito dazito - 15 days ago 12
Android Question

DialogFragment with a custom title

I need to place a custom title to my

DialogFragment
.

getDialog().setTitle("My Title");


is not enough for me because I want to change the title text and background colors.

As you can see from the image below, with
getDialog().setTitle("My Title");
I've no customization (as far as I know), ie, the text color is black and the background is white.

My objective is to have
My Title
customized as seen by
Custom Title
. I've been looking around the API and I couldn't find any method to load a view into the title section.

Anyone knows how can I customize or set/inject a view into the
FragmentDialog
?

enter image description here

Answer

You have to create a custom dialog by overiding onCreateDialog like so:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();

    dialogView = inflater.inflate(R.layout.dialog_change_password, null);

    /* Anything that needs to be done to the view, ie. 
    on click listeners, postivie/negative buttons,
    values being changed etc */

    builder.setView(dialogView);
    return builder.create();
}

and the dialog_change_password.xml:

 <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@color/white_grey">

    <TextView
        android:text="@string/change_password"
        android:id="@+id/title"
        style="@style/dialogHeading" />


    <LinearLayout
        android:layout_marginTop="10dp"
        style="@style/dialogSection">

        <LinearLayout
            style="@style/PasswordChangeRow">

            <TextView
                style="@style/PasswordChangeLabel"
                android:text="@string/new_password"/>

            <EditText
                style="@style/PasswordChangeField"
                android:id="@+id/password"
                android:inputType="textPassword"/>

        </LinearLayout>

        <LinearLayout
            style="@style/PasswordChangeRow">

            <TextView
                style="@style/PasswordChangeLabel"
                android:text="@string/confirm_password"/>

            <EditText
                style="@style/PasswordChangeField"
                android:id="@+id/confirmPassword"
                android:inputType="textPassword"/>

        </LinearLayout>
    </LinearLayout>

    <TextView
        android:text="@string/password_conditions_message"
        style="@style/dialogMessage" />

</LinearLayout>

Obviously that xml is a bit more complex that what is needed but is just an example of what can be done, it looks like this

enter image description here

Comments