Display rupee symbol via strings xml not working - android

I using the following string entry in strings.xml file to display rupee symbol.
<string name="current_amount">"Balance: ₹%.2f"</string>
It displays a square rather than the actual symbol on Android 2.2.
Please help.
PS: I am testing it on an emulator for Android 2.2, I don't have a 2.2 device.

[EDIT] Working soultion for Android 2.2
Ok here's how you can get it to work. You'll have to download the font Rupee_Foradian.ttf from here and put it in the assets folder.
Then, place this line in strings.xml file
<string name="rs">`</string>
And finally set the Typeface using this code:
TextView t = (TextView) findViewById(R.id.text);
Typeface face = Typeface.createFromAsset(getAssets(), "Rupee_Foradian.ttf");
t.setTypeface(face);
t.setText("Balance " + getResources().getString(R.string.rs));
[Original] Doesn't work on Android 2.2
Put this line in your strings.xml file
<string name="rs">\u20B9</string>
In your code, for example, if you're assigning it to a TextView do this:
TextView text = (TextView) findViewById(R.id.text);
text.setText("Balance " + getResources().getString(R.string.rs) + VALUE);

<string name="current_amount">Balance: ₹</string>
I have tried this and it works

You need to ensure you are using a font that can display this unicode character.
You can change the font of your views as follows:
In your main activity MainActivity.java
public static final String PREF_MYFONT = "DejaVuSansCondensed.ttf";
In your view where you need to display the Rupee symbol MyView.java
#Override
public void onStart() {
super.onStart();
myTitle=(TextView) getActivity().findViewById(R.id.title);
myDescription=(TextView) getActivity().findViewById(R.id.description);
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), MainActivity.PREF_MYFONT);
myTitle.setTypeface(font);
myDescription.setTypeface(font);
}

pendingApprovalReceiptPaymentFragmentBinding.tvAmountValue.setText(getResources().getString(R.string.Rs)+" "+Integer.toString(pendingApprovalListModel.getAmount()));

Related

How to set google font programmatically in Android

How to set google font programmatically in Android
App is crash Caused by:
android.content.res.Resources$NotFoundException: Font resource ID
#0x7f090002 could not be retrieved.
val typeface = ResourcesCompat.getFont(applicationContext, R.font.halant)
appVersionName.typeface = typeface
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:app="http://schemas.android.com/apk/res-auto"
app:fontProviderAuthority="com.google.android.gms.fonts"
app:fontProviderPackage="com.google.android.gms"
app:fontProviderQuery="Halant"
app:fontProviderCerts="#array/com_google_android_gms_fonts_certs">
</font-family>
Though above two answers are correct, I will give you step-by-step details about "Downloadable Fonts" so that other will understand.
Note: A device must have Google Play services version 11 or higher to
use the Google Fonts provider.
In the Layout Editor, select a TextView, and then under Properties, select fontFamily > More Fonts.
Select the font want and make sure you choose create downloadable font (creates xml file in your font folder) and click OK.
Android Studio automatically generates the relevant XML files that are
needed to render the font correctly in your app.
Now, you can directly add it in TextView like this:
android:fontFamily="#font/halant_light"
Or use Downloadable Fonts programmatically like this:
val request = FontRequest(
"com.google.android.gms.fonts",
"com.google.android.gms",
"Halant", //your font
R.array.com_google_android_gms_fonts_certs
)
val callback = object : FontsContract.FontRequestCallback() {
override fun onTypefaceRetrieved(typeface: Typeface) {
// Your code to set the font goes here
}
override fun onTypefaceRequestFailed(reason: Int) {
// Your code to deal with the failure goes here
}
}
FontsContractCompat.requestFont(mContext, request, callback, mHandler)
If you don't want the above programmatic way you can use the below code which I tested and working perfectly:
val typeface = ResourcesCompat.getFont(applicationContext, R.font.halant_light)
fontText.typeface = typeface
val typeface = Typeface.create("sans-serif-condensed", Typeface.BOLD)
textView.typeface = typeface

Textview fromHtml bold tag not properly shown

I am using fromHtml for some words, but it not properly shown.Sorry my bad english.
Typeface tfArial = Typeface.createFromAsset(getAssets(), "arialtur.otf");
String yazi="Deneme "+"<strong>"+"must be bold"+"</strong>"+" kayıt.";
Spanned text1 = Html.fromHtml(yazi);
TextView aa= (TextView) findViewById(R.id.metin1);
TextView ab= (TextView) findViewById(R.id.metin2);
aa.setText(text1);
aa.setTypeface(tfArial);
ab.setText("Non arial font");
screenshot http://hizliresim.com/rd4gkV
In case of <b> tag in resourses string you could wrap text in <![CDATA[ and ]]>, i.e.:
<string name="textWithBold"><![CDATA[<b>BoldText</b>]]></string>
Then you could get and show it so:
textView.setText(Html.fromHtml(getString(R.string.textWithBold)));
<strong> HTML tag is not a "styling" tag. It's here only to indicates that the content is important. The default style of the <strong> relies on the web engine implementation.
You can have some information on these two links :
http://www.w3schools.com/tags/tag_strong.asp
What's the difference between <b> and <strong>, <i> and <em>?
Try to use <b> instead of <strong> if you want a bold text.
you can do this several ways like
Typeface tfArial =Typeface.createFromAsset(getAssets(),"arialtur.otf");
String yazi="Deneme <strong> must be bold </strong> kayıt.";
// OR String yazi="Deneme <b> must be bold </b> kayıt.";
TextView aa= (TextView) findViewById(R.id.metin1);
TextView ab= (TextView) findViewById(R.id.metin2);
aa.setText(Html.fromHtml(yazi));
aa.setTypeface(tfArial);
//OR aa.setTypeface(tfArial,Typeface.BOLD);
ab.setText("Non arial font");
Example :
using strong tag
Deneme must be bold kayıt.
using b tag
Deneme must be bold kayıt
Try this.
String message ="Deneme "+"<b>"+"must be bold"+"</b>"+" kayıt.";
aa.setText(Html.fromHtml(message));
You can also do same thing from XML by useing of HTML tag

How to place hyperlink to a website on android app?

I want to place a hyperlink on android app that I am developing.
I tried this:
main.xml
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="#string/hyperlink"
android:id="#+id/hyperlink"
android:autoLink="web"
>
</TextView>
The strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">WebLink</string>
<string name="hyperlink">http://google.com</string>
</resources>
But the problem is, the link looks like this: http://google.com and I don't want to show the actual url.
1) How to replace link by text like "Click Here to visit Google" and the text is linked with the website url ?
2) How to place email address (same question, how to replace it with text something like "Click Here to Email" and the text should be linked with email#domain.com)
I also tried this tutorial: http://coderzheaven.com/2011/05/10/textview-with-link-in-android/
But I am getting following error messages:
Description Resource Path Location Type
http cannot be resolved to a variable MyLink.java /MyLink/src/com/MyLink line 21 Java Problem
Syntax error on token "" <br /> <a href="", ? expected after this token MyLink.java /MyLink/src/com/MyLink line 21 Java Problem
Type mismatch: cannot convert from String to boolean MyLink.java /MyLink/src/com/MyLink line 20 Java Problem
Use the default Linkify class.
Here is an Example and the code from the tutorial:
This is my sample code for you, I think this will solve your problem:
public class StackOverflowActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 1) How to replace link by text like "Click Here to visit Google" and
// the text is linked with the website url ?
TextView link = (TextView) findViewById(R.id.textView1);
String linkText = "Visit the <a href='http://stackoverflow.com'>StackOverflow</a> web page.";
link.setText(Html.fromHtml(linkText));
link.setMovementMethod(LinkMovementMethod.getInstance());
// 2) How to place email address
TextView email = (TextView) findViewById(R.id.textView2);
String emailText = "Send email: Click Me!";
email.setText(Html.fromHtml(emailText));
email.setMovementMethod(LinkMovementMethod.getInstance());
}
}

Unicode characters not displayed in TextView.setText

I can't get a TextView to correctly dynamically display unicode characters, and it's driving me batty. I've stripped it down to the bare minimum, but the TextView populated by setText still shows diamonds with question marks inside them for the unicode characters. The version populated from strings.xml shows the multibyte characters perfectly. Here's the activity:
public class TestMultibyteActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
setContentView( R.layout.main );
TextView textField = (TextView) findViewById( R.id.text_field );
String str = "Tübingen systemportefølje";
Log.d( "MULTIBYTE", str ); //note that this prints the multibyte chars correctly.
//EDIT: oh crap, no it doesn't. might be onto something here...
textField.setText( str );
}
}
And here's the layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="#+id/text_field"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/unicodechars"/>
</LinearLayout>
Here's strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">TestMultibyteActivity</string>
<string name="unicodechars">Tübingen systemportefølje</string>
</resources>
I'm building with ant. Here's my default.properties:
target=Google Inc.:Google APIs:8
And here's my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mycompany.android.multibyte"
android:versionCode="1"
android:versionName="1.0">
<application android:label="#string/app_name" android:icon="#drawable/icon">
<activity android:name="TestMultibyteActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I've tinkered with everything I can think of, but it seems like unicode characters are getting split by the CharSequence interface, and I can't figure out why.
Unfortunately, you just can't do it that way from strings.xml AFAIK.
You're left doing one of two things.
Adding the Unicode character within java to the String in the XML file:
String str = "\u00A9" + getContext().getString(R.string.your_string);
Entering the text as HTML in java:
yourTextView.setText(Html.fromHtml("your chars"));
Hope this is useful.
The accepted answer is correct but Html.fromHtml is deprecated now. So you'll need to use:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
textView.setText(Html.fromHtml(user.getInput(), Html.FROM_HTML_MODE_LEGACY));
} else {
textView.setText(Html.fromHtml(user.getInput()));
}
It could be done in such a simple way:
str.replace("uoo26","&");
I had problems trying to display Unicode character from a custom font that were mapped in the Unicode private area. This is a common area where fonts like MaterialDesign and FontAwesome map their icon font characters. Just for clarity I was testing this on an android version 4.4.2 so maybe this is not an issue on later versions (but probably is). I had tried all combinations of "\uF151", &#xF151, and I also tried the Html.fromHtlm. None of these techniques worked to properly display the characters in the Unicode private area. If I keep myself to the range \u00xx, they all worked fine for the fonts that had Unicode codes in those locations. (The two fonts I've mentioned don't have any symbols mapped to those point locations)
In examining the font using Microsoft's Character Map I noticed that the characters in the Unicode private area space where not showing up when I had the Windows-English character set chosen for the fonts. The characters would show up if I selected the Unicode character set; and in the case of the Material Design font if I selected the Japanese character set.
What I did to get the character to display on the in TextView was to change the Locale to Japanese, call setText on the Textview object passing it the correct private area unicode value and the character then displayed correctly. So here's the code I used to set icon font symbol and then revert back to English:
TextView tv = (TextView)findViewById(R.id.myTextViewObject);
Typeface tf = Typeface.createFromAsset(this.getAssets(), "material_design.ttf");
tv.setTypeface(tf);
String x = "\uE693";
tv.setText(x);
setDefaultLocale(getApplicationContext(),"en");
tv.append("hello");
And here's the code for the setDefaultLocale method:
public static void setDefaultLocale(Context context, String locale) {
Locale locJa = new Locale(locale.trim());
Locale.setDefault(locJa);
Configuration config = new Configuration();
config.locale = locJa;
context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
locJa = null;
config = null;
}
In the case of FontAwesome, you have to select the Tradition Chinese character set to get access to the unicode private area code points.
You might ask, why I didn't select the "Unicode" character set? The character set that android uses is based on the current locale and I couldn't find a way to select unicode as the current locale. In addition, I couldn't find a way to map the private area unicodes into my existing Locale. I also can't tell you whether this is a issue on how these True Type Fonts where constructed or whether this is an Android issue (albeit I think there should have been a why to map the private area code for use in your existing locale) What I have learned is that all Unicode code points are mapped into all language locales for the same font. That's the thing that I think confuses a lot of people about fonts that support unicode. The windows character map was a useful tool for me in determining which character points are mapped into which character set.
Welcome to the world of kotlin,
If someone wants to set a UNICODE programmatically, you can do it the following way
Unicode character for 🤚is U+1F91A
Replace U+ with 0x which makes it 0x1F91A
val unicodeChar = 0x1F91A.toChar() // unicode for 🤚
For the above question user wants to display "Tübingen systemportefølje"
val char1 = 0x00FC.toChar() // unicode for ü is U+00FC
val char2 = 0x00F8.toChar() // unicode for ø is U+00F8
val name = StringBuilder("T")
.append(char1)
.append("bingen systemportef")
.append(char2)
.append("lje")
.toString()
// OUTPUT name = "Tübingen systemportefølje"
Now you can set the string to your Textview.
For dynamic string, you can search for pattern beginning with 0x and replace it by constructing an equivalent Unicode image.
If you want to show text from unicode.
First step, remove "\u" from unicode. Eg: \u00A9 should be "00A9"
Then, convert "00A9" to Integer. Eg:val hexVal =
Integer.parseInt("00A9", 16)
Finally, convert Integer to char. val char = hexVal.toChar().Then
show char.
Source code:
val builder = StringBuilder()
listUnicodes.forEach
{ uniCode ->
val hexVal = Integer.parseInt(uniCode, 16)
val char = hexVal.toChar()
builder.append(char)
}
return builder.toString()
I tried every other answer in here, it couldn't resolved mine. finally i found it :D
StringEscapeUtils.unescapeJava("Your unicode string")

Set font at runtime, TextView

How to set the font of a TextView created at runtime?
I created a TextView
Textview tv = new TextView(this);
tv.setTextSize(20);
I can easily change the size, now I'd like to set font style to "Verdana".
How to do this?
To set In-built Font at Run-Time:
First of all, To Change Font-face, a Typeface class is used.
Now, at Run-Time, to set the font-face, Use setTypeface(Typeface) from the Java code
at Design-Time, to set the font-face, Use android:typeface="serif"
For example:
<TextView android:text="#+id/TextView01"
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30px"
android:textStyle="italic"
android:typeface="serif" />
To set Custom font(s) in your Android application
To do this, simply create an assets/ folder in the project root, and put your fonts (in TrueType, or TTF, form) in the assets. You might, for example, create assets/fonts/ and put your TTF files in there:
TextView tv=(TextView)findViewById(R.id.custom);
Typeface face=Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf");
tv.setTypeface(face);
You can have .ttf font in your asset folder. Say font's name is "default.ttf" and you just now have to write below 2 lines of code
TextView text = new TextView(this);
text.setTypeface(Typeface.createFromAsset(getAssets(), "default.ttf"));
You must also we careful because different font have different sizes. You may need to set size as :
text.setTextSize(20);
you can use your font which you have store in font "res/font"
ex. for API level 16 and above.
Typeface typeface = ResourcesCompat.getFont(context, R.font.rubik_medium);
txtView.setTypeface(typeface);
you can also use
Typeface typeface = getResources().getFont(R.font.rubik_medium);
txtView.setTypeface(typeface);
but it support with API level 26 and above.
With introduction of Fonts in XML in Android 8.0 (backward compatible from API version 14) its very easy to set font from xml itself.
From the android documentation:
Android 8.0 (API level 26) introduces a new feature, Fonts in XML,
which lets you use fonts as resources. You can add the font file in
the res/font/ folder to bundle fonts as resources. These fonts are
compiled in your R file and are automatically available in Android
Studio. You can access the font resources with the help of a new
resource type, font. For example, to access a font resource, use
#font/myfont, or R.font.myfont.
Firstly create a Android Resource Directory in res folder named as font
Add your .ttf font file to that directory, and then create font family
Create a font family
A font family is a set of font files along with its style and weight details. In Android, you can create a new font family as an XML resource and access it as a single unit, instead of referencing each style and weight as separate resources. By doing this, the system can select the correct font based on the text style you are trying to use.
To create a font family, perform the following steps in the Android Studio:
Right-click the font folder and go to New > Font resource file. The
New Resource File window appears.
Enter the file name, and then click OK. The new font resource XML
opens in the editor.
Enclose each font file, style, and weight attribute in the <font>
element. The following XML illustrates adding font-related
attributes in the font resource XML:
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
<font
android:fontStyle="normal"
android:fontWeight="400"
android:font="#font/lobster_regular" />
<font
android:fontStyle="italic"
android:fontWeight="400"
android:font="#font/lobster_italic" />
</font-family>
Then use the following code to set font in your textView like
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/lobster"/>
Here is a small utility class
public class TypefaceHelper {
public static void setViewGroupTypeface(ViewGroup container, Typeface typeface) {
final int children = container.getChildCount();
for (int i = 0; i < children; i++)
View child = container.getChildAt(i);
if (child instanceof TextView) {
setTextViewTypeface((TextView) child, typeface);
} else if (child instanceof ViewGroup) {
setViewGroupTypeface((ViewGroup) child, typeface);
}
}
}
public static void setTextViewTypeface(TextView textView, Typeface typeface) {
textView.setTypeface(typeface);
}
}
For things like Spinners or ListViews (i.e. any kind of AdapterView) which generate their children from an adapter you will need to set the typeface of each item View in the getView (or similar) method of the adapter. This is because views may be created as needed and so setting the Typeface in onCreate won't work properly.
Dynamically you can set the fontfamily similar to android:fontFamily in xml by using this,
For Custom font:
TextView tv = ((TextView) v.findViewById(R.id.select_item_title));
Typeface face=Typeface.createFromAsset(getAssets(),"fonts/mycustomfont.ttf");
tv.setTypeface(face);
For Default font:
tv.setTypeface(Typeface.create("sans-serif-medium",Typeface.NORMAL));
These are the list of default font family used, use any of this by replacing the double quotation string "sans-serif-medium"
FONT FAMILY TTF FILE
1 casual ComingSoon.ttf
2 cursive DancingScript-Regular.ttf
3 monospace DroidSansMono.ttf
4 sans-serif Roboto-Regular.ttf
5 sans-serif-black Roboto-Black.ttf
6 sans-serif-condensed RobotoCondensed-Regular.ttf
7 sans-serif-condensed-light RobotoCondensed-Light.ttf
8 sans-serif-light Roboto-Light.ttf
9 sans-serif-medium Roboto-Medium.ttf
10 sans-serif-smallcaps CarroisGothicSC-Regular.ttf
11 sans-serif-thin Roboto-Thin.ttf
12 serif NotoSerif-Regular.ttf
13 serif-monospace CutiveMono.ttf
"mycustomfont.ttf" is the ttf file. Path will be in src/assets/fonts/mycustomfont.ttf
If you don't want to use typeface and fiddle around with the path to your font file (Which may crash your application if you put in an incorrect path), here's another way.
First create a style in your styles.xml
<style name="YourFont">
<item name="android:fontFamily">#font/your_font</item>
</style>
Then you can just add the style using
textView.setTextAppearance(context, R.style.YourFont);
You need to use Typeface:
add font you wish to use to your project as asset.
create Typeface object using that font:
Typeface myFont = Typeface.createFromAsset(getAssets(), "fonts/MyFont.ttf");
set typeface to the object you'd like to customize:
TextView myTextView = (TextView)findViewById(R.id.my_text_view);
myTextView.setTypeface(myFont);
You can use the following code to set all your text to a specific font at runtime. Just call the setViewGroupFont method at the end of your Activity onCreate method or whenever you dynamically create new views:
private static final String FONT_NAME = "fonts/Roboto-Regular.ttf";
private static Typeface m_font = null;
public static Typeface getFont(Context p_context)
{
if (null == m_font && null != p_context)
{
m_font = Typeface.createFromAsset(p_context.getApplicationContext().getAssets(), FONT_NAME);
}
return m_font;
}
public static void setViewGroupFont(ViewGroup p_viewGroup)
{
if (null != p_viewGroup)
{
for (int currChildIndex = 0; currChildIndex < p_viewGroup.getChildCount(); currChildIndex++)
{
View currChildView = p_viewGroup.getChildAt(currChildIndex);
if (ViewGroup.class.isInstance(currChildView))
{
setViewGroupFont((ViewGroup) currChildView);
}
else
{
try
{
Method setTypefaceMethod = currChildView.getClass().getMethod("setTypeface", Typeface.class);
setTypefaceMethod.invoke(currChildView, getFont(p_viewGroup.getContext()));
}
catch (NoSuchMethodException ex)
{
// Do nothing
}
catch (Exception ex)
{
// Unexpected error setting font
}
}
}
}
}

Categories

Resources