I am developing an Android app to support both En/Ar. But I faced a problem that if the user changes from En to Ar the alignment of the user interface must turns from "left to right" to "right to left".
Example: (TextView)(EditText) this is in En
But in Ar it should be: (EditText)(TextView).
Is there a way to do this without creating two different layouts or two different versions?
I've tried to take some of the horror out of this by creating a set of custom
LabeledView
components (for Form components such asCheckBox
,EditText
andSpinners
). These views (such asLabledEditText
) inflates a region-specific layout and implements the bare minimum of calls in order to act as a facade (EditText
in this case).The
View
class itself contains:This should at least cut down any duplication as you should now be able to reference the
LabeledEditText
view rather than anTextView
andEditText
combo.In my implementation which I haven't fully shown I've gone a step further and created an abstract
LabeledView
class which uses some custom attributes allowing me to customise both label and value in specific situations (see thealign(attrs);
line of code). Depending on how big your app is you might want to try something similar?Why can't this be done with two layouts (you never said why this is not desireable)? As described by the Android Developers documentation
Ref: http://developer.android.com/guide/topics/resources/localization.html
So in your case create
res/layout-ar
then copy your existing layout into this folder and then simply swap them round. Simple, follows best practices and is easy to do. This also makes any further localisation changes easier going forward without having to write more code.If you were to write code you are going to need to find the default language of the device and then swap the Views based on this. You can get the language by:
See this question for more detail: Get the current language in device
On a final personal note: I think the former is a much better separation of concerns, as the code provides logic and the XML layouts actually control the layout (with Android selecting the right resources automagically for you without having to write any more code).
Why not just make the TextView above the EditText?
Android 4.2 introduced native support for
right to left
layout.AndroidManifest
set theandroid:supportsRtl="true"
Here is the video with detailed explanation: https://youtu.be/plW1qSGDSzs