Question

I'm working an Android app and want to translate it to Persian language. All String values in the project are saved into an resource XML file. Some String values are used in layout files and some in classes (R.String). When using Persian text in Android, it has to be reshaped to be displayed correctly.

I want to reshape all resource String values without calling reshape method for every String value.

Can anyone explain me how to do this?

Some idea:
override String class
override getResource class

Was it helpful?

Solution

Android provides already functionality (well documented) to have a multilanguage app. Instead of replacing your text and having severall versions of your app for each language, its better to use the frameworks function. In that case the app chooses a suitable language from the available languages you provided depending on the device locale settings.

So basically you would start by creating the required directory structure (link above):

MyProject/
    res/
       values/
           strings.xml
       values-fa/
           strings.xml

and then you fill in String values into the files, e.g.:

English (default locale), /values/strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="title">My Application</string>
    <string name="hello_world">Hello World!</string>
</resources>

Persian, /values-fa/strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="title">...</string>
    <string name="hello_world">...</string>
</resources>

(quoted and adapted from the link above)

Solution for reshape farsi language
The reshape function has to be used for every Farsi String value, so setting string in the XML layout isn't possible (AFAIK), so the following proposals assume, that all String values are set programatically.

Using a global static wrapper function #1

public static final String getLocalizedString(int resId) {
  if(Locale.getDefault().toString().equals("fa_IR")) {
       return PersianReshape.reshape(getResources().getString(resId));
  }else{
      return getResources().getString(resId);
}

You can now use this function to load the String (you have to change each occurence) or you override e.g. the getRessource method. I personally would prefer using a static function instead of overriding because of possible other problems regarding loading resources of other type than String, side effects etc.

Creating a custom class with overriding setText() for each used ui widgets #2
Another possibility is to create custom ui widgets that do a call to PersianReshape.reshape() when display. E.g. for EditText:

class CustomTextField extends EditText {
    @Override
    public void setText(String text) {
        super.setText(PersianReshape.reshape(text));
    }
}
[...]
CustomTextField myTextBox = new CustomTextField();
myTextBox.setText("....");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top