调整AlertDialog文本

时间:2018-07-18 21:43:23

标签: android textview android-alertdialog android-dialogfragment

我在DialogFragment中有一个通用AlertDialog的类,可以正常工作。例如,我用它来弹出“关于”对话框。

问题是对话框中的文本不合理,因此看起来不太好。 有什么办法可以证明文字的正确性?意思是将其左右对齐?

这是我代码中的相关功能:

@Override
public AlertDialog onCreateDialog(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Resources res = getActivity().getResources();
    String title = getArguments().getString("title");
    String message = getArguments().getString("message");
    String yesButton = getArguments().getString("yes_button");
    String noButton = getArguments().getString("no_button");
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), android.R.style.Theme_Material_Dialog_Alert);
    if (!noButton.equals(""))
        builder.setNegativeButton(noButton, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                mCancel.run();
            }
        });
    builder.setIcon(R.mipmap.my_launcher)
            .setTitle(title.equals("") ? res.getString(R.string.app_name) : title)
            .setMessage(message)
            .setPositiveButton(yesButton, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    mConfirm.run();
                }
            });
    AlertDialog dialog = builder.create();
    dialog.show();
    // text MATCH_PARENT
    TextView messageView = (TextView)dialog.findViewById(android.R.id.message);
    LinearLayout.LayoutParams messageViewLL = (LinearLayout.LayoutParams) messageView.getLayoutParams();
    messageViewLL.width = ViewGroup.LayoutParams.MATCH_PARENT;

    // If only positive button, center it.
    if (noButton.equals("")) {
        Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
        LinearLayout.LayoutParams positiveButtonLL = (LinearLayout.LayoutParams) positiveButton.getLayoutParams();
        positiveButtonLL.width = ViewGroup.LayoutParams.MATCH_PARENT;
    }
    return dialog;
}

1 个答案:

答案 0 :(得分:1)

如果您要对齐标题/消息文本,则可以使用以下方法来代替.setTitle(String)和{{1},而不是.setCustomTitle(View).setMessage(String)

.setView(View)