Right justify text in AlertDialog
This is an old question, but there is a very simple solution. Assuming you are using MinSdk 17
, you can add this to your styles.xml
:
<style name="AlertDialogCustom" parent="ThemeOverlay.AppCompat.Dialog.Alert">
<item name="android:layoutDirection">rtl</item>
</style>
And in the AlertDialog.Builder
you just need to specify this AlertDialogCustom
in the constructor:
new AlertDialog.Builder(this, R.style.AlertDialogCustom)
.setTitle("Your title?")
.show();
As far as I can see from the code of AlertDialog
and AlertController
you can't access the TextView
s responsible for message and title.
You can use reflection to reach mAlert
field in AlertDialog instance, and then again use reflection to access mMessage
and mTitle
fields of mAlert
. Though I wouldn't recommend this approach as it relies on internals (which might change in future).
As another (and probably much better) solution, you can apply custom theme via AlertDialog
constructor. This would allow you to right-justify all TextView
s in that dialog.
protected AlertDialog (Context context, int theme)
This should be easier and more robust approach.
Here is step by step instructions:
Step 1. Create res/values/styles.xml
file. Here its content:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="RightJustifyTextView" parent="@android:style/Widget.TextView">
<item name="android:gravity">right|center_vertical</item>
</style>
<style name="RightJustifyDialogWindowTitle" parent="@android:style/DialogWindowTitle" >
<item name="android:gravity">right|center_vertical</item>
</style>
<style name="RightJustifyTheme" parent="@android:style/Theme.Dialog.Alert">
<item name="android:textViewStyle">@style/RightJustifyTextView</item>
<item name="android:windowTitleStyle">@style/RightJustifyDialogWindowTitle</item>
</style>
</resources>
Step 2. Create RightJustifyAlertDialog.java
file. Here its content:
public class RightJustifyAlertDialog extends AlertDialog
{
public RightJustifyAlertDialog(Context ctx)
{
super(ctx, R.style.RightJustifyTheme);
}
}
Step 3. Use RightJustifyAlertDialog
dialog:
AlertDialog dialog = new RightJustifyAlertDialog(this);
dialog.setButton("button", new OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
}
});
dialog.setTitle("Some Title");
dialog.setMessage("Some message");
dialog.show();
Step 4. Check the results: