Android AlertDialog title centered

Many methods on the Internet are implemented using the setCustomTitle method. I prefer not to do so because I have already found the textView of the title:

You can get the title after show (note that you can only get it after show, and it will be empty after create):

TextView titleView = dialog.findViewById(androidx.appcompat.R.id.alertTitle);

Then during the debugging process, set the background for it and confirm that its width matches the container. Then ideally, it would be ok to set a centered attribute titleView.setGravity(Gravity.CENTER) for it, but you will find that it has no effect.

In fact, you can see it in the source code layout:

<androidx.appcompat.widget.DialogTitle
            android:id="@+id/alertTitle"
            style="?android:attr/windowTitleStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="start"
            android:ellipsize="end"
            android:singleLine="true"
            android:textAlignment="viewStart"/>

It sets a textAlignment property to indicate the alignment of the text. So it will make setGravity seem to be ineffective. Then we set its alignment to center alignment and it’s OK:

titleView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);

Originally, I wanted to declare this textAlignment uniformly for windowTitleStyle in style, but I also found that it did not take effect. From the layout source code above, we can see that textAlignment is set after setting this style, so the textAlignment you define in style will be replaced later. , so it can only be centered through dynamic code settings.

over.

Guess you like

Origin blog.csdn.net/qq_35584878/article/details/132181154