Número en árabe en texto árabe en Android

EDITAR

Estoy portando mi aplicación a la localidad árabe. Tengo algunos getString () con parámetros como:

getString(R.string.distance, distance) 

Donde <string name="distance">%1d km</string>

El requisito es que en árabe debería mostrarlo así: "2.3 كم".

Si establezco como el escenario para Arabia Saudita (país = "sa") o EAU (país = "ae") el número se muestran en la India, pero mi cliente quiere que en árabe.

La solución aquí es usar a Egipto como un país en el escenario, pero esto no es posible para mí.

Lo intenté:

 @TargetApi(Build.VERSION_CODES.LOLLIPOP) public void setAppContextLocale(Locale savedLocale) { Locale.Builder builder = new Locale.Builder(); builder.setLocale(savedLocale).setExtension(Locale.UNICODE_LOCALE_EXTENSION, "nu-latn"); Locale locale = builder.build(); Configuration config = new Configuration(); config.locale = locale; config.setLayoutDirection(new Locale(savedLocale.getLanguage())); mAppContext.getResources().updateConfiguration(config, mContext.getResources().getDisplayMetrics()); } 

Como se sugiere en esta pregunta, pero después de que el país se ignora por lo tanto SA y AE locales utilizar las cadenas en el archivo predeterminado.

Hay tal problema en el bugtracker de Google: los números arábigos en árabe intead lenguaje del sistema numeral hindú-árabe

Si la localidad de Egipto en particular no funciona debido a problemas de algunos clientes (lo entiendo), entonces puede dar formato a su cadena a cualquier otro idioma occidental. Por ejemplo:

  NumberFormat nf = NumberFormat.getInstance(new Locale("en","US")); //or "nb","No" - for Norway String sDistance = nf.format(distance); distanceTextView.setText(String.format(getString(R.string.distance), sDistance)); 

Si la solución con la nueva Locale no funciona en absoluto, hay una solución fea:

 public String replaceArabicNumbers(String original) { return original.replaceAll("١","1") .replaceAll("٢","2") .replaceAll("٣","3") .....; } 

(Y las variaciones a su alrededor con coincidencias Unicodes (U + 0661, U + 0662, …) Ver más ideas similares aquí )

Actualizar1: Para evitar llamar a las cadenas de formato uno por uno en todas partes, sugeriría crear un pequeño método de herramienta:

 public final class Tools { static NumberFormat numberFormat = NumberFormat.getInstance(new Locale("en","US")); public static String getString(Resources resources, int stringId, Object... formatArgs) { if (formatArgs == null || formatArgs.length == 0) { return resources.getString(stringId, formatArgs); } Object[] formattedArgs = new Object[formatArgs.length]; for (int i = 0; i < formatArgs.length; i++) { formattedArgs[i] = (formatArgs[i] instanceof Number) ? numberFormat.format(formatArgs[i]) : formatArgs[i]; } return resources.getString(stringId, formattedArgs); } } .... distanceText.setText(Tools.getString(getResources(), R.string.distance, 24)); 

O reemplazar el TextView defecto y manejarlo en setText(CharSequence text, BufferType type)

 public class TextViewWithArabicDigits extends TextView { public TextViewWithArabicDigits(Context context) { super(context); } public TextViewWithArabicDigits(Context context, AttributeSet attrs) { super(context, attrs); } @Override public void setText(CharSequence text, BufferType type) { super.setText(replaceArabicNumbers(text), type); } private String replaceArabicNumbers(CharSequence original) { if (original != null) { return original.toString().replaceAll("١","1") .replaceAll("٢","2") .replaceAll("٣","3") ....; } return null; } } 

Espero que ayude

Establece tu TypeFace como sigue para Arabic

 Typeface font = Typeface.createFromAsset(getAssets(), "fonts/abcd.TTF"); 

Abcd es fuente árabe.

 textview.setTypeface(font); 
 The default Locale is constructed statically at runtime for your application process from the system property settings, so it will represent the Locale selected on that device when the application was launched. Typically, this is fine, but it does mean that if the user changes their Locale in settings after your application process is running, the value of getDefaultLocale() probably will not be immediately updated. If you need to trap events like this for some reason in your application, you might instead try obtaining the Locale available from the resource Configuration object, ie Locale current = getResources().getConfiguration().locale; You may find that this value is updated more quickly after a settings change if that is necessary for your application. // please try below code double distance = 2.3; // ex. distance is 2.3 Locale current = getResources().getConfiguration().locale; //get current locale Log.d("Locale", current + " "); if(current.toString().equals("ar_EG")){ //for arabic char[] arabicChars = {'٠','١','٢','٣','٤','٥','٦','٧','٨','٩'}; StringBuilder builder = new StringBuilder(); String str="2.3"; for(int i =0;i<str.length();i++) { if(Character.isDigit(str.charAt(i))) { builder.append(arabicChars[(int)(str.charAt(i))-48]); } else { builder.append(str.charAt(i)); } } Log.d("Locale"," " +builder.toString()+" كم"); // get distance in arabic كم ٢.٣ }else if (current.toString().equals("en_US")){ Log.d("Locale"," " +distance+" KM"); // get distance in us english 2.3 KM } 
  • Cambiar la configuración regional en el emulador de Android
  • La configuración de Android cambia de forma aleatoria al valor predeterminado
  • Cómo configurar el texto del cuadro de diálogo de google api en el idioma predeterminado de la aplicación
  • Android: ¿Cómo mantener la configuración local de la aplicación independiente de System Locale?
  • ¿Puedo acceder a recursos de diferentes idiomas de Android?
  • ¿Por qué Locale.getDefault (). GetLanguage () en Android devuelve el nombre para mostrar en lugar del código de idioma?
  • Android obtiene la configuración actual, no predeterminada
  • Obtener locales disponibles para tts
  • Configuración de idioma turco e inglés: traducir caracteres turcos a equivalentes latinos
  • Hablar con TTS como Hindi
  • Texto de Android a voz en diferentes idiomas
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.