javaandroidnavigation-drawerright-to-leftleft-to-right

Best practice to place menu Icons on the left side of the navigation drawer in Persian,Hebrew devices?


I am trying to have a navigation drawer that opens from the right. ( i managed to do that using LAYOUT_GRAVITY="END"). Now I want all the menu items to start from the right and also their Icons on the right too.

enter image description here

To do that I added (SUPPORTSRTL="TRUE") to the manifest and that also solved the problem. But here is the problem:

To solve that I had to set the (LAYOUTDIRECTION="LTR") to the root element of layouts on every one of my actitives. That solved the problem and now everything is in the position I desired, however this doesn't seem like a sustainable solution to add this line of code to root element of each activity I will ever add to my app. Can you please tell me if this is the best way to do it or not?

I found other questions with the same topic with no accepted proper answers.


Solution

  • this line of code should solve your problem

        ViewCompat.setLayoutDirection(drawer, ViewCompat.LAYOUT_DIRECTION_RTL);
    

    drawer is a reference to your DrawerLayout.

    an other way to force RTL layout to activities is using styles xml. this is how i whould do it:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    
    <style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    
    </style>
    
    <style name="ShaliRTL" parent="AppTheme">
        <item name="android:layoutDirection">rtl</item>
    </style>
    
    </resources>
    

    then in android manifest apply this new style (ShaliRTL) to your specific activity:

            <activity
            android:name=".YourActivity"
            android:label="@string/title_activity_settings"
            android:theme="@style/ShaliRTL"
            android:screenOrientation="fullSensor" />
    

    good luck.