Right justify text in AlertDialog

前端 未结 6 1078
逝去的感伤
逝去的感伤 2020-12-06 04:52

Is it possible to right-justify the text in an AlertDialog\'s title and message?

I am showing Hebrew messages but they are showing up left justified.

6条回答
  •  粉色の甜心
    2020-12-06 05:44

    After struggling with this for an hour (the solutions above didn't work for me), I managed to align the AlertDialog's title and message to the right, without overriding any styles, simply changing the gravity and layout params.

    In DialogFragment:

    @Override
    public void onStart() {
        super.onStart();
    
        // Set title and message
        try {
            alignDialogRTL(getDialog(), this);
        }
        catch (Exception exc) {
            // Do nothing
        }
    }
    

    The actual function:

    public static void alignDialogRTL(Dialog dialog, Context context) {
        // Get message text view
        TextView message = (TextView)dialog.findViewById(android.R.id.message);
    
        // Defy gravity
        message.setGravity(Gravity.RIGHT);
    
        // Get title text view
        TextView title = (TextView)dialog.findViewById(context.getResources().getIdentifier("alertTitle", "id", "android"));
    
        // Defy gravity (again)
        title.setGravity(Gravity.RIGHT);
    
        // Get title's parent layout
        LinearLayout parent = ((LinearLayout)Title.getParent());
    
        // Get layout params
        LinearLayout.LayoutParams originalParams = (LinearLayout.LayoutParams)parent.getLayoutParams();
    
        // Set width to WRAP_CONTENT
        originalParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
    
        // Defy gravity (last time)
        originalParams.gravity = Gravity.RIGHT |  Gravity.CENTER_VERTICAL;
    
        // Set updated layout params
        parent.setLayoutParams(originalParams);
    }
    

提交回复
热议问题