Android开发求助:设置欧元符号却显示英镑符号的问题
Hey there! I totally get why this is confusing—your initial TextView shows the euro symbol, but when you trigger the displayPrice method, it switches to pounds. Let's break down the issue and fix it step by step.
Why This Happens
The NumberFormat.getCurrencyInstance() method uses your device's system locale settings by default to determine which currency symbol to display. If your phone is set to a locale that uses pounds (like English (United Kingdom)), the formatter will automatically use the pound symbol, overriding your initial hardcoded €0 text.
Solutions to Force Euro Symbol
Option 1: Use an Euro-Area Locale
You can explicitly pass a locale from a country that uses euros (like France, Germany, or Italy) to the currency formatter. This ensures the euro symbol is used regardless of the device's system settings:
// This method displays the given price on the screen with euro symbol private void displayPrice(int number) { TextView priceTextView = (TextView) findViewById(R.id.price_text_view); // Use a euro-zone locale (e.g., France) to enforce euro formatting NumberFormat euroFormatter = NumberFormat.getCurrencyInstance(Locale.FRANCE); priceTextView.setText(euroFormatter.format(number)); }
Option 2: Explicitly Set the Currency to Euro
If you want to keep the number formatting style (like decimal separators) matching the device's locale but force the euro symbol, you can set the currency directly on the formatter:
// This method displays the given price on the screen with euro symbol private void displayPrice(int number) { TextView priceTextView = (TextView) findViewById(R.id.price_text_view); NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(); // Force the formatter to use Euro currency currencyFormatter.setCurrency(Currency.getInstance("EUR")); priceTextView.setText(currencyFormatter.format(number)); }
Quick Note About Price Values
If your number variable represents cents (e.g., 0 = €0.00, 50 = €0.50), remember to convert it to a decimal value before formatting:
// Convert cents to euros priceTextView.setText(euroFormatter.format(number / 100.0));
Example XML (For Reference)
Just to recap your initial layout code:
<TextView android:id="@+id/price_text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="€0" android:textAllCaps="true" android:layout_marginTop="16dp" android:textSize="16sp" android:textColor="@android:color/black"/>
内容的提问来源于stack exchange,提问作者furkan sedat

