I\'m developing an Android application.
How can I center the title for a custom dialog that I\'m using?
In Kotlin, you can do it in 1 line
dialog!!.window!!.attributes = dialog!!.window!!.attributes.apply { dimAmount = 0F }
If you don't call AlertDialog.Builder.setIcon()
and AlertDialog.Builder.setTitle()
, then your custom dialog will not show the built-in/default title View. In this case you are able to add your custom title View:
AlertDialog.Builder.setView(View view)
As soon as it is you who create this View it is possible to implement any type of alignment.
Try this:
TextView titleText = (TextView) helpDialog.findViewById(R.id.alertTitle);
if(titleText != null) {
titleText.setGravity(Gravity.CENTER);
}
Full code (using android.support.v7.app.AlertDialog
):
AlertDialog.Builder helpDialogBuilder = new AlertDialog.Builder(context)
.setTitle(/*your title*/)
.setMessage(/*your message*/)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/*you can do something here*/
dialog.dismiss();
}
})
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
/*you can do something here*/
dialog.dismiss();
}
});
final AlertDialog helpDialog = helpDialogBuilder.create();
helpDialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
TextView titleText = (TextView) helpDialog.findViewById(R.id.alertTitle);
if(titleText != null) {
titleText.setGravity(Gravity.CENTER);
}
TextView messageText = (TextView) helpDialog.findViewById(android.R.id.message);
if(messageText != null) {
messageText.setGravity(Gravity.CENTER);
}
}
});
helpDialog.show();
TextView titleView = (TextView) dialog.findViewById(android.R.id.title);
if(titleView != null) {
titleView.setGravity(Gravity.CENTER);
}
See this KodeCenter article on Android Dialog and AlertDialog for more details.
Here's a nasty solution.... Extend AlertDialog.Builder and override all the methods (eg. setText, setTitle, setView, etc) to not set the actual Dialog's text/title/view, but to create a new view within the Dialog's View do everything in there. Then you are free to style everything as you please.
To clarify, as far as the parent class is concerned, the View is set, and nothing else.
As far as your custom extended class is concerned, everything is done within that view.
You can do it in code as well. Assume you have dialog fragment then add following lines of code.
@Override
public void onStart()
{
super.onStart();
TextView textView = (TextView) this.getDialog().findViewById(android.R.id.title);
if(textView != null)
{
textView.setGravity(Gravity.CENTER);
}
}