如何在视图中显示波斯语(波斯语)数字

How to display Persian(Farsi) numbers in views

我想在视图中显示波斯语(波斯语)数字。例如,我计算了一个日期并将其转换为 Jalali 日历,但如何用波斯数字显示它?

您可以创建自定义视图并在其上附加波斯语字体,最后您可以在 xml views.most 波斯语字体在字符映射中没有英文数字,​​您可以简单地使用它而没有任何问题。例如:

public class TextViewStyle extends TextView {

    public TextViewStyle(Context context) {
        super(context);
        init(context, null, 0);
    }


    public TextViewStyle(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
        init(context, attrs, 0);
    }


    public TextViewStyle(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    private void init(Context context, AttributeSet attrs, int defStyle){
        try {
            TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.TextViewStyle, defStyle, 0);
            String str = a.getString(R.styleable.TextViewStyle_fonttype);
            switch (Integer.parseInt(str)) {
                case 0:
                    str = "fonts/byekan.ttf";
                    break;
                case 1:
                    str = "fonts/bnazanin.ttf";
                    break;
                case 2:
                    str = "fonts/btitr.ttf";
                    break;
                case 3:
                    str = "fonts/mjbeirut.ttf";
                    break;
                case 4:
                    str = "fonts/bnazanin_bold.ttf";
                    break;
                default:
                    str = "fonts/bnazanin.ttf";
                    break;
            }
            setTypeface(FontManager.getInstance(getContext()).loadFont(str));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

attr.xml :

<declare-styleable name="TextViewStyle">
    <attr name="selected_background" format="integer"/>
    <attr name="fonttype">
        <enum name="byekan" value="0"/>
        <enum name="bnazanin" value="1"/>
        <enum name="btitr" value="2"/>
        <enum name="mjbeirut" value="3"/>
        <enum name="bnazaninBold" value="4"/>
    </attr>
</declare-styleable>

通过使用字体 class 可以将视图的字体类型更改为波斯语字体,这样数字就可以用波斯语字体显示了:

Typeface typeface = Typeface.createFromAsset(getAssets(), "FarsiFontName.ttf");
myView.setTypeface(typeface);

另一种用波斯字体显示数字的方法是使用以下助手 Class:

public class FormatHelper {

    private static String[] persianNumbers = new String[]{ "۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹" };


    public static String toPersianNumber(String text) {
        if (text.length() == 0) {
            return "";
        }
        String out = "";
        int length = text.length();
        for (int i = 0; i < length; i++) {
        char c = text.charAt(i);
        if ('0' <= c && c <= '9') {
            int number = Integer.parseInt(String.valueOf(c));
            out += persianNumbers[number];
        }
        else if (c == '٫') {
            out += '،';
        }
        else {
            out += c;
        }

        return out;
    }
}

将这个class保存为UTF8格式,像下面的代码一样使用

FormatHelper.toPersianNumber(numberString);

将区域设置设置为阿拉伯语、埃及

int i = 25;
NumberFormat nf = NumberFormat.getInstance(new Locale("ar","EG"));
nf.format(i);

您必须在 windows 中添加波斯语标准键盘,并在您要输入波斯语数字和单词时更改为此键盘。 这对我有用

您可以使用以下方法以波斯语显示数字:

 public String NumToPersion(String a){
    String[] pNum =new String[]{"۰","۱","۲","۳","۴","۵","۶","۷","۸","۹" };
    a=a.replace("0",pNum[0]);
    a=a.replace("1",pNum[1]);
    a=a.replace("2",pNum[2]);
    a=a.replace("3",pNum[3]);
    a=a.replace("4",pNum[4]);
    a=a.replace("5",pNum[5]);
    a=a.replace("6",pNum[6]);
    a=a.replace("7",pNum[7]);
    a=a.replace("8",pNum[8]);
    a=a.replace("9",pNum[9]);
   return a;
}

只需在 kotlin 中为无符号整数执行此操作

fun toPersian(n:Int) : String{
val p="۰۱۲۳۴۵۶۷۸۹"
return n.toString().trim().map{
    p[it.toString().trim().toInt()]
}.joinToString()
}
txt_view?.text=toPersian(12087)//۱۲۰۸۷

简单而正确的方法是使用LocaleString.format。如果默认字体不支持波斯数字,您可以简单地为视图使用波斯字体。这是我的做法。

Locale locale = new Locale("fa");
return String.format(locale, "%04d", year) + "/" + 
       String.format(locale, "%02d", month) + "/" + 
       String.format(locale, "%02d", day);

您还可以使用 PersianCaldroid 库,它不仅为您提供像 PersianDate.toStringInPersian() 这样的简单 API,还让您拥有波斯语 DatePicker 和 CalendarView。

在键入 EditText 时试试这个:

 public static void edtNumE2P(final EditText edt) {
    edt.addTextChangedListener(new TextWatcher() {

      @Override
      public void onTextChanged(CharSequence s, int pstart, int pbefore, int pcount) {
//        for (String chr : new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}) {
        for (char chr : "0123456789".toCharArray()) {
          if (s.toString().contains("" + chr)) {
            edt.setText(MyUtils.numE2P(edt.getText().toString()));
            edt.setSelection(edt.getText().length());
          }
        }
      }


      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {

      }


      @Override
      public void afterTextChanged(Editable s) {
      }
    });
  }

也试试这个:

    public static String numE2P(String str, boolean reverse) {
    String[][] chars = new String[][]{
      {"0", "۰"},
      {"1", "۱"},
      {"2", "۲"},
      {"3", "۳"},
      {"4", "۴"},
      {"5", "۵"},
      {"6", "۶"},
      {"7", "۷"},
      {"8", "۸"},
      {"9", "۹"}
    };

    for (String[] num : chars) {
      if (reverse) {
        str = str.replace(num[1], num[0]);
      } else {
        str = str.replace(num[0], num[1]);
      }
    }
//    Log.v("numE2P", str);
    return str;
  }

可以用Time4J显示日期,用ChronoFormatter显示:

ChronoFormatter<PersianCalendar> formatter= ChronoFormatter.setUp(PersianCalendar.axis(), PERSIAN_LOCALE)
.addPattern("dd", PatternType.CLDR).build();
// it will display day :  ۲۴

.addPattern("dd MMMM", PatternType.CLDR).build();
// مرداد ۲۴

通过定义模式,您可以选择日期显示方式:ChronoFormatter

Kotlin Version 通过 Extension Property

如果您想显示每种类型的数字(例如 IntDoubleFloat) 在波斯语或阿拉伯语数字中,使用这些扩展属性确实有帮助:


PersianUtils.kt

/**
 * @author aminography
 */

val Number.withPersianDigits: String
    get() = "$this".withPersianDigits

val String.withPersianDigits: String
    get() = StringBuilder().also { builder ->
        toCharArray().forEach {
            builder.append(
                when {
                    Character.isDigit(it) -> PERSIAN_DIGITS["$it".toInt()]
                    it == '.' -> "/"
                    else -> it
                }
            )
        }
    }.toString()

private val PERSIAN_DIGITS = charArrayOf(
    '0' + 1728,
    '1' + 1728,
    '2' + 1728,
    '3' + 1728,
    '4' + 1728,
    '5' + 1728,
    '6' + 1728,
    '7' + 1728,
    '8' + 1728,
    '9' + 1728
)


用法:

println("Numerical 15   becomes: " + 15.withPersianDigits)
println("Numerical 2.75 becomes: " + 2.75.withPersianDigits)

println("Textual 470  becomes: " + "470".withPersianDigits)
println("Textual 3.14 becomes: " + "3.14".withPersianDigits)

结果:

Numerical 15   becomes: ۱۵
Numerical 2.75 becomes: ۲/۷۵

Textual 470  becomes: ۴۷۰
Textual 3.14 becomes: ۳/۱۴

最简单的方法是使用 NumberFormat :

NumberFormat numberFormat = NumberFormat.getInstance(new Locale("fa","IR"));
textView.setText(numberFormat.format(15000))

要管理应用程序语言(英语/波斯语),应用程序中使用的字体必须正确转换并显示波斯语和英语中的数字。

这就是我们使用 setTypeface() 方法的原因:

public class MyTextView extends TextView {
        public MyTextView (Context context, AttributeSet attrs) {
            super(context, attrs);
            Typeface typeface = Typeface.createFromAsset(context.getAssets(), "fonts/iransans_fa_number_regular.ttf");
            setTypeface(typeface);
        }
    }

当应用程序的语言发生变化时,我们会更改 MyTextView 中使用的字体:

public static String iranSansRegular;

public static void setLocale(Resources res, Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences("Configuration", 0);
        String appLang = sharedPreferences.getString("appLanguage", Locale.getDefault().getLanguage());

        if (appLang.equals("fa")) {
            iranSansRegular = "fonts/iransans_fa_number_regular.ttf";
        } else {
            iranSansRegular = "fonts/iransans_en_number_regular.ttf";
        }

        Locale myLocale = new Locale(appLang);
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        Locale.setDefault(myLocale);
        conf.setLayoutDirection(myLocale);
        res.updateConfiguration(conf, dm);
    }

并使用 iranSansRegular 设置字体:

public class MyTextView extends TextView {
        public MyTextView (Context context, AttributeSet attrs) {
            super(context, attrs);
            Typeface typeface = Typeface.createFromAsset(context.getAssets(), iranSansRegular);
            setTypeface(typeface);
        }
    }