带有自定义标题的 DialogFragment

DialogFragment with a custom title

我需要为我的 DialogFragment 添加自定义标题。

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

对我来说不够,因为我想更改标题文本和背景颜色。

如下图所示,getDialog().setTitle("My Title");我没有自定义(据我所知),即文本颜色为黑色,背景为白色。

我的 objective 是 My Title 定制的 Custom Title。我一直在查看 API,但找不到任何方法将视图加载到标题部分。

任何人都知道如何自定义或set/inject FragmentDialog 视图?

您必须像这样重写 onCreateDialog 来创建自定义对话框:

@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();
}

和 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>

显然 xml 比需要的要复杂一些,但这只是可以完成的示例,它看起来像这样

您可以使用 setCustomTitle 方法,您可以在其中扩充您自己的完全自定义布局

示例

import android.support.v4.app.DialogFragment;

public class PromoDetailDialogFragment extends DialogFragment {

    public Dialog onCreateDialog(Bundle savedInstanceState) {
        View titleView = getActivity().getLayoutInflater().inflate(R.layout.my_title, null);

        TextView tv = (TextView) titleView.findViewById(R.id.my_title_textView);
        tv.setText("title");

        AlertDialog dialog = new AlertDialog.Builder(getContext())
                .setCustomTitle(titleView)
                .setMessage("message")
                .setCancelable(true)
                .create();

        return dialog;
    }
}

这种方式更干净也更强大