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

34

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


您可能需要使用一些dll或第三方工具来获取波斯语字体。 - Itban Saeed
13个回答

25

显示使用波斯语字体的数字的另一种方法是使用以下Helper 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;
    }
}

将该类保存为UTF8格式,并像以下代码一样使用它

FormatHelper.toPersianNumber(numberString);

如果你在数字上进行计算,那会让事情变得困难。因为当你需要进行计算时,你必须将它们转换回去。但是使用字体则不需要进行转换和反转换。 - Hojat Modaresi

15

通过使用Typeface类,可以将视图的字体类型更改为波斯语字体,以便数字可以用波斯语字体显示:

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

1
请将您的评论翻译成英语 - Mir Hussain
该方法并不实际建议。 - Manian Rezaee
@Akbar Rezaee,为什么? - omid
好的,但我认为这个解决方案只适用于已经将数字保存为UTF-8的情况。 - Ayub

5

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

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

4

您可以创建自定义视图并在其上附加波斯语字体,最后您可以将其用于 XML 视图。大多数波斯语字体在字符映射中没有英文数字,并且您可以简单地使用它而不会出现任何问题。例如:

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>

在这种情况下,我们只需要波斯数字,而不是所有字符,因此我建议创建一个数组并手动输入波斯数字。 - Manian Rezaee

4

• 通过扩展属性实现Kotlin版本

如果你想在波斯或阿拉伯数字中显示所有类型的数字(例如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)

Result:

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

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

3

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

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

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

3

最简单、最容易的方法是使用NumberFormat

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

1
这个答案更有思想性,谢谢! - Ehsan

2

在编辑文本时,尝试使用以下方法:

 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;
  }

2
你可以使用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


对于 Android,我宁愿使用 Time4A(姐妹项目)。还有几种显示波斯数字的方法,可以选择适合伊朗的区域设置,或者修改格式化程序,例如: chronoFormatter.with(Attributes.NUMBER_SYSTEM, NumberSystem.ARABIC_INDIC_EXT) - Meno Hochschild

1
你可以使用以下方法将数字显示为波斯语:
 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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接