Wednesday, November 12, 2014

Force RTL layouts in Android

Yup. I'm writing a Persian oriented application. Of course I should provide RTL layouts in my application and use Iranian locale. So what to do? In my custom Application class I use this to change the locale:

   @Override public void onCreate(){  
     super.onCreate();  
   
     Configuration newConfig = new Configuration();  
     newConfig.locale = new Locale("fa");  
     Locale.setDefault(newConfig.locale);  
     super.onConfigurationChanged(newConfig);  
     getBaseContext().getResources().updateConfiguration(newConfig, getResources().getDisplayMetrics());  
   }

For the RTL layout part, I use this approach to force RTL on SDK v17+:
First  add this option to Application section in AndroidManifest.xml:

 android:supportsRtl="true"  

Now add implement this function whereever in your application and call it on all Activity.onCreate event handlers:

 import android.annotation.TargetApi;  
 import android.os.Build;  
 import android.view.View;  
 import android.view.Window;  
   
 /**  
  * Created by Klaus on 11/13/2014.  
  */  
 public class RTLProvider {  
   @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)  
   static public void forceRTLIfSupported(Window win)  
   {  
     if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){  
       win.getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);  
     }  
   }  
 }  

No comments:

Post a Comment