I'm new in android working on an app that gives the user info about all font's of Google.
For that, I need to make an app with a TextView Something like this
On click of the TextView, the font will change With text.
I'm thinking about using onclicklistener
you can put "your_font.ttf" file in asset folder then import it with
Typeface custom_font_1 = Typeface.createFromAsset(getAssets(), "your_font.ttf");
then assign it to your showCaseTextView with this
showCaseTextView.setTypeFace(custom_font_1);
then in your onClickListener of showCaseTextView to change your specifiedTextView font do like this
specifiedTextView.setTypeFace(custom_font_1);
and repeat it for other fonts.
You can implement your own custom font with TextView, EditText, Button etc.. by using android attributes.
How to
-Here are some steps to use:
1.Create attribute file (res->values->attrs.xml)
<?xml version="1.0" encoding="UTF-8"?>
<resources>
<declare-styleable name="TextElement">
<attr name="font" format="string"/>
<attr name="underline" format="boolean"/>
</declare-styleable>
</resources>
2.Create Custom TextView class (anywhere in java folder)
3. Use attributes inside your layout file
4. and just run your code.
Here is the full example of your question, you can go through this exmaple:
Full Demonstration
Have 2 way to archive this
1st way
public class FontCache {
private static HashMap<String, Typeface> fontCache = new HashMap<>();
public static Typeface getTypeface(String fontname, Context context) {
Typeface typeface = fontCache.get(fontname);
if (typeface == null) {
try {
typeface = Typeface.createFromAsset(context.getAssets(), fontname);
} catch (Exception e) {
return null;
}
fontCache.put(fontname, typeface);
}
return typeface;
}
}
This caches the fonts while minimizing the number of accesses to the assets. Now, since we've a method to access our custom font, let's implement a class, which extends TextView.
Extending TextView
Next, we'll create a new Java class, which extends TextView. This allows us to use that class in all XML views. It inherits all functionality and properties of a regular TextView; but adds our custom font.
Once again, we're taking a peek at the source code of our eat foody project. The code might look complex for a second, but is straight-forward:
public class EatFoodyTextView extends TextView {
public EatFoodyTextView(Context context) {
super(context);
applyCustomFont(context);
}
public EatFoodyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
applyCustomFont(context);
}
public EatFoodyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
applyCustomFont(context);
}
private void applyCustomFont(Context context) {
Typeface customFont = FontCache.getTypeface("SourceSansPro-Regular.ttf", context);
setTypeface(customFont);
}
}
The first three methods are just constructors, which we override to call a single method applyCustomFont(). That method is the important piece of the puzzle. It simply gets the (hopefully cached) font from our FontCache class. Lastly, we've to call setTypeface() with the font and we're almost done. In case you're wondering, we can call the setTypeface() directly (and not on a TextView object), since we're extending the TextView class.
Using the Class
You might wonder, if so much preparation is worth the effort. In this section you'll see that it is indeed. Because all you've left to do is use the class in an XML view and it automatically has your custom font. There is no Java code necessary!
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.futurestudio.foody.views.EatFoodyTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/eat_foody_green_dark"
android:textSize="20sp"
android:text="Future Studio Blog"
android:layout_marginBottom="24dp"/>
</RelativeLayout>
As you can see, you can continue to use all niceties (e.g. textSize, textColor) of TextView. Now, just replace all elements with the class we just created, for example and you applied your custom font everywhere!
(Ref: https://futurestud.io/tutorials/custom-fonts-on-android-extending-textview)
2nd way
Follow Google guide support from API 26 (Android 8) https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml
Make change between textview to change font
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textview_normal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/eat_foody_green_dark"
android:textSize="20sp"
android:text="Future Studio Blog"
android:layout_marginBottom="24dp"/>
<com.futurestudio.foody.views.EatFoodyTextView
android:id="#+id/textview_custom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/eat_foody_green_dark"
android:textSize="20sp"
android:text="Future Studio Blog"
android:visibility="gone"
android:layout_marginBottom="24dp"/>
</RelativeLayout>
attention at android:visibility="gone"
in Activity you use this code to toggle between 2 TextViews
final TextView normalTextView = findViewById(R.id.textview_normal);
final TextView customTextView = findViewById(R.id.textview_custom);
normalTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
normalTextView.setVisibility(View.GONE);
customTextView.setVisibility(View.VISIBLE);
}
});
customTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
normalTextView.setVisibility(View.VISIBLE);
customTextView.setVisibility(View.GONE);
}
});
Related
I've created a custom control which is a subclass of LinearLayout. I have also created a layout file on which this control is based. Finally I have defined attributes which I parse in the constructor to set my custom properties on. As an example, one of those properties is called 'text'.
Here's a simplified version of my code (I've stripped out a lot of the other properties and such so we can just focus on the one property 'text'):
First, the class (our custom version of a RadioButton)...
public class RadioButton extends LinearLayout
{
private TextView textView;
public RadioButton(Context context, AttributeSet attrs)
{
super(context, attrs);
initAttributes(attrs, 0);
}
private void initAttributes(AttributeSet attrs, int defStyle)
{
final TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.CheckBoxView, defStyle, 0);
text = a.getString(R.styleable.RadioButton_text);
if(text == null)
text = "Not set";
a.recycle();
}
#Override
protected void onFinishInflate()
{
super.onFinishInflate();
textView = (TextView)findViewById(R.id.textView);
textView.setText(text);
}
private String text;
public String getText() { return text; }
public void setText(String newValue)
{
text = newValue;
if(textView != null)
textView.setText(text);
}
}
Here's the attrs.xml file...
<resources>
<attr name="text" format="string" />
<declare-styleable name="RadioButton">
<attr name="text" />
</declare-styleable>
</resources>
And here's the 'reusable_radiobutton.xml' layout file (Note: the internal RadioButtonView is a custom-rendered View and works fine):
<?xml version="1.0" encoding="utf-8"?>
<com.somedomain.reusable.ui.RadioButton
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical">
<com.somedomain.reusable.ui.RadioButtonView
android:id="#+id/radioButtonView"
style="#style/DefaultRadioButtonView" />
<TextView
android:id="#+id/textView"
style="#style/DefaultRadioButtonText" />
</com.somedomain.reusable.ui.RadioButton>
With the above, users of my control can simply include it in their own layout files, like so...
<include android:id="#+id/someRadioButton"
layout="#layout/reusable_radiobutton" />
The in their code, using the following, they can get that instance and do with it what they wish, like so...
RadioButton someRadioButton = (RadioButton)findViewById(R.id.someRadioButton);
someRadioButton.text = "Woot!";
This works as expected.
However, this doesn't...
<include android:id="#+id/someRadioButton"
layout="#layout/reusable_radiobutton"
app:text="Hello World!" />
It gives me a warning, but otherwise ignores it.
I then tried this...
<com.somedomain.reusable.ui.RadioButton
app:text="Hello World!" />
While this does instantiate my control and does pass 'Hello World!' to my property via the attributes, nothing actually loads or even associates the layout file to my class so nothing appears on the screen!
So how can I create a custom view, based on a layout, which other developers can simply reference in their own layout files while also allowing them to set custom attributes?
Hope that all made sense! :)
Note: The Android documentation talks about exactly what I'm after, 'Compound Controls' as referenced here, but they don't give an example of using a layout to define the compounded control. However, I feel that was pretty close.
Found it here on SO. I didn't realize you could inflate something into yourself. That and using the Merge tag took care of it for me.
I've found several posts regarding this topic, but all of this topics either sets the font with setTypeFace() method on a TextView object, or creating a custom class which sets the font to Roboto and extends TextView. As far as I know from API-Level 11(?) or something, we are able to set the TypeFace as a xml attribute, some how. Like this:
<TextView
android:id="#+id/profileHeader"
android:layout_width="100dp"
android:layout_height="100dp"
android:typeface="roboto"
android:text="Hello, world">
</TextView>
What is the right way to do this? Is it possible to have a fallback if the application runs on a device lower than API level 11(?) something like:
android:typeface="roboto|monospace|serif"
Take a look at the RobotoTextView project. Works down to Android 1.5, and you can set the typeface using XML attributes. It also includes other views like RobotoButton, RobotoCheckbox, etc.
I don't see a way you can define an external typeface as a xml attribute. You should store the typeface in the assets and call:
tv.setTypeface( Typeface.createFromAsset( context.getAssets(), roboto.ttf ) );
You can not set font directly from assets like this you have to do as follow in onCreate. This will make same thing what you want to do.
TextView tvTextView = (TextView) findViewById(R.id.textView1);
Typeface typeface = Typeface.createFromAsset(getAssets(),"Roboto.ttf");
tvTextView.setTypeface(typeface);
Hope it will help you out.:D
The android:typeface attribute only has a few valid options (according to the Android docs)...
normal
sans
serif
monospace
If you need the Roboto font in your app for older devices, you need to include the Roboto TTF files into your project.
The most obvious way to use these fonts is to use the setTypeface() method of TextView, but if you want to specify it in XML instead, you must create a custom TextView and create your own styleable attribute for your custom TextView.
This topic is all over the Internet.
For JellyBean (4.1) onward you can use the method provided in this StackOverflow topic. It will fallback gracefully to sans in older devices.
If you must fallback to monospace or serif, declare a folder layout-v16 where you use the font you chose, i.e., "sans-serif-condensed", and in the default folder you use the "monospace" or "serif" font.
If you want to fallback to a non-default font, you can programatically check the android version and choose the appropriate action, i.e.:
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
TextView textView = (TextView) findViewById(R.id.textView_id);
Typeface myFont = Typeface.createFromAsset(getAssets(),"RobotoCondensed.ttf");
textView.setTypeface(myFont);
}
This is for future people running in to the same issue as I have. Setting typeface tends to take up lot of memory when it comes to loading multiple rows. Using the following two codes together to actually make it work smoothly. I got the solution from stackoverflow but they answers were not listed together.
public class RobotoTextView extends TextView {
Context context;
public RobotoTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context = context;
}
public RobotoTextView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
public RobotoTextView(Context context) {
super(context);
this.context = context;
}
public void setTypeface(Typeface tf, int style) {
if (!isInEditMode()) {
if (style == Typeface.NORMAL) {
super.setTypeface(TypeFaceProvider.getTypeFace(getContext(), "fonts/Roboto-Light.ttf"));
} else if (style == Typeface.ITALIC) {
super.setTypeface(TypeFaceProvider.getTypeFace(getContext(), "fonts/Roboto-LightItalic.ttf"));
} else if (style == Typeface.BOLD) {
super.setTypeface(TypeFaceProvider.getTypeFace(getContext(), "fonts/Roboto-Bold.ttf"));
} else if (style == Typeface.BOLD_ITALIC) {
super.setTypeface(TypeFaceProvider.getTypeFace(getContext(), "fonts/Roboto-BoldItalic.ttf"));
}
}
}
public class TypeFaceProvider {
private static Hashtable<String, Typeface> sTypeFaces = new Hashtable<String, Typeface>(
4);
public static Typeface getTypeFace(Context context, String fileName) {
Typeface tempTypeface = sTypeFaces.get(fileName);
if (tempTypeface == null) {
tempTypeface = Typeface.createFromAsset(context.getAssets(),
fileName);
sTypeFaces.put(fileName, tempTypeface);
}
return tempTypeface;
}
}
I'm trying to use Font Awesome on my application, I was able to integrate the font using Typeface.createFromAsset(), but I also want to use the icons provided by this font, but so far I haven't been able to do that.
This particular font contains icons inside the Unicode Private Use Area (PUA), for things like media player controls, file system access, arrows, etc.
Has anybody used fonts that contain icons and symbols on Android, is this possible at all?
Font Awesome seems to be working fine for me in my android app. I did the following:
Copied fontawesome-webfont.ttf into my assests folder
Found the character entities for icons I wanted, using this page: http://fortawesome.github.io/Font-Awesome/cheatsheet/
Created an entry in strings.xml for each icon. Eg for a heart:
<string name="icon_heart"></string>
Referenced said entry in the view of my xml layout:
<Button
android:id="#+id/like"
style="?android:attr/buttonStyleSmall"
...
android:text="#string/icon_heart" />
Loaded the font in my onCreate method and set it for the appropriate Views:
Typeface font = Typeface.createFromAsset( getAssets(), "fontawesome-webfont.ttf" );
...
Button button = (Button)findViewById( R.id.like );
button.setTypeface(font);
Try IcoMoon: http://icomoon.io
Pick the icons you want
Assign characters to each icon
Download the font
Say, you picked the play icon, assigned the letter 'P' to it, and downloaded the file icomoon.ttf to your asset folder. This is how you show the icon:
xml:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="48sp"
android:text="P" />
java:
Typeface typeface = Typeface.createFromAsset(getAssets(), "icomoon.ttf");
textView.setTypeface(typeface);
I've given a talk on making beautiful Android apps, which includes explanation on using icon fonts, plus adding gradients to make the icons even prettier:
http://www.sqisland.com/talks/beautiful-android
The icon font explanation starts at slide 34:
http://www.sqisland.com/talks/beautiful-android/#34
Maybe too late but I had the same need so I've published this https://github.com/liltof/font-awsome-for-android
It's an android ready xml version of font awesome usable just like Keith Corwin said
Hope it will help others.
As above is great example and works great:
Typeface font = Typeface.createFromAsset(getAssets(), "fontawesome-webfont.ttf" );
Button button = (Button)findViewById( R.id.like );
button.setTypeface(font);
BUT! > this will work if string inside button you set from xml:
<string name="icon_heart"></string>
button.setText(getString(R.string.icon_heart));
If you need to add it dynamically can use this:
String iconHeart = "";
String valHexStr = iconHeart.replace("&#x", "").replace(";", "");
long valLong = Long.parseLong(valHexStr,16);
button.setText((char) valLong + "");
If you want programmatic setText without add string to string.xml
see its hexadecimal code here:
http://fortawesome.github.io/Font-Awesome/cheatsheet/
replace to 0xf066
Typeface typeface = Typeface.createFromAsset(getAssets(), "fontawesome-webfont.ttf");
textView.setTypeface(typeface);
textView.setText(new String(new char[]{0xf006 }));
There is small and useful library designed for this purposes:
dependencies {
compile 'com.shamanland:fonticon:0.1.9'
}
Get demo on Google Play.
You can easily add font-based icon in your layout:
<com.shamanland.fonticon.FontIconView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/ic_android"
android:textSize="#dimen/icon_size"
android:textColor="#color/icon_color"
/>
You can inflate font-icon as Drawable from xml:
<?xml version="1.0" encoding="utf-8"?>
<font-icon
xmlns:android="http://schemas.android.com/apk/res-auto"
android:text="#string/ic_android"
android:textSize="#dimen/big_icon_size"
android:textColor="#color/green_170"
/>
Java code:
Drawable icon = FontIconDrawable.inflate(getResources(), R.xml.ic_android);
Links:
Project page
Github repo
I made this helper class in C# (Xamarin) to programmatically set the text property. It which works pretty well for me:
internal static class FontAwesomeManager
{
private static readonly Typeface AwesomeFont = Typeface.CreateFromAsset(App.Application.Context.Assets, "FontAwesome.ttf");
private static readonly Dictionary<FontAwesomeIcon, string> IconMap = new Dictionary<FontAwesomeIcon, string>
{
{FontAwesomeIcon.Bars, "\uf0c9"},
{FontAwesomeIcon.Calendar, "\uf073"},
{FontAwesomeIcon.Child, "\uf1ae"},
{FontAwesomeIcon.Cog, "\uf013"},
{FontAwesomeIcon.Eye, "\uf06e"},
{FontAwesomeIcon.Filter, "\uf0b0"},
{FontAwesomeIcon.Link, "\uf0c1"},
{FontAwesomeIcon.ListOrderedList, "\uf0cb"},
{FontAwesomeIcon.PencilSquareOutline, "\uf044"},
{FontAwesomeIcon.Picture, "\uf03e"},
{FontAwesomeIcon.PlayCircleOutline, "\uf01d"},
{FontAwesomeIcon.SignOut, "\uf08b"},
{FontAwesomeIcon.Sliders, "\uf1de"}
};
public static void Awesomify(this TextView view, FontAwesomeIcon icon)
{
var iconString = IconMap[icon];
view.Text = iconString;
view.SetTypeface(AwesomeFont, TypefaceStyle.Normal);
}
}
enum FontAwesomeIcon
{
Bars,
Calendar,
Child,
Cog,
Eye,
Filter,
Link,
ListOrderedList,
PencilSquareOutline,
Picture,
PlayCircleOutline,
SignOut,
Sliders
}
Should be easy enough to convert to Java, I think. Hope it helps someone!
One of the libraries that I use for Font Awesome is this:
https://github.com/Bearded-Hen/Android-Bootstrap
Specifically,
https://github.com/Bearded-Hen/Android-Bootstrap/wiki/Font-Awesome-Text
The documentation is easy to understand.
First, add the needed dependencies in the build.gradle:
dependencies {
compile 'com.beardedhen:androidbootstrap:1.2.3'
}
Secondly, you can add this in your XML:
<com.beardedhen.androidbootstrap.FontAwesomeText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
fontawesometext:fa_icon="fa-github"
android:layout_margin="10dp"
android:textSize="32sp"
/>
but make sure you add this in your root layout if you want to use above code example:
xmlns:fontawesometext="http://schemas.android.com/apk/res-auto"
The FontView library lets you use normal/unicode font characters as icons/graphics in your app. It can load the font via assets or a network location.
The benefit of this library is that:
1 - it takes care of remote resources for you
2 - scales the font size in dynamically sized views
3 - allows the font to easily be styled.
https://github.com/shellum/fontView
Example:
Layout:
<com.finalhack.fontview.FontView
android:id="#+id/someActionIcon"
android:layout_width="80dp"
android:layout_height="80dp" />
Java:
fontView.setupFont("fonts/font.ttf", character, FontView.ImageType.CIRCLE);
fontView.addForegroundColor(Color.RED);
fontView.addBackgroundColor(Color.WHITE);
There's another nice solution which you can use in your layout xml files directly and does not require to use setTypeface.
It is Joan Zapata's Iconify. You can read here what's new in Iconify v2. It includes 9 different font libraries which you can simply use by adding dependencies to your build.gradle file.
In the layout xml files it's possible to choose between these widgets:
com.joanzapata.iconify.widget.IconTextview
com.joanzapata.iconify.widget.IconButton
com.joanzapata.iconify.widget.IconToggleButton
Initially create asset folder and copy the fontawesome icon (.ttf)
How to create asset folder?
app-->right Click -->new-->folder --> asset folder
next step download how to download .ttf file?
click here--> and click download button after download extract and open web fonts. finally choose true text style(ttf)paste asset folder.
how to design xml and java file in android ?
app-->res-->values
string.xml
resources
string name="calander_font" > <string
resources
this example of one font more Unicode click here
Activity_main.xml
<TextView
android:layout_width="30dp"
android:layout_height="30dp"
android:id="#+id/calander_view"/>
MainActivity.java
calander_tv = (TextView)findViewById(R.id.calander_view);
Typeface typeface = Typeface.createFromAsset(getAssets(),"/fonts/fa-solid-900.ttf");
calander_tv.setTypeface(typeface);
calander_tv.setText(R.string.calander_font);
Output:
Output image
I'm a bit late to the party but I wrote a custom view that let's you do this, by default it's set to entypo, but you can modify it to use any iconfont: check it out here: github.com/MarsVard/IconView
//
edit the library is old and not supported anymore...
new one here https://github.com/MarsVard/IonIconView
In case you only need a few font awesome icons, you can also use http://fa2png.io to generate normal pixel images. But if you add new icons/buttons regularly I'd recommend the .ttf version as its more flexible.
If someone wonders how to add it programmitcally you gotta do it this way.
button_info.setText(R.string.icon_heart);
button_info.append(" Hallo"); //<<--- This is the tricky part
As all answers are great but I didn't want to use a library and each solution with just one line java code made my Activities and Fragments very messy.
So I over wrote the TextView class as follows:
public class FontAwesomeTextView extends TextView {
private static final String TAG = "TextViewFontAwesome";
public FontAwesomeTextView(Context context) {
super(context);
init();
}
public FontAwesomeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public FontAwesomeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public FontAwesomeTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void setCustomFont(Context ctx, AttributeSet attrs) {
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewPlus);
String customFont = a.getString(R.styleable.TextViewPlus_customFont);
setCustomFont(ctx, customFont);
a.recycle();
}
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fontawesome-webfont.ttf");
setTypeface(tf);
}
}
public boolean setCustomFont(Context ctx, String asset) {
Typeface typeface = null;
try {
typeface = Typeface.createFromAsset(ctx.getAssets(), asset);
} catch (Exception e) {
Log.e(TAG, "Unable to load typeface: "+e.getMessage());
return false;
}
setTypeface(typeface);
return true;
}
}
what you should do is copy the font ttf file into assets folder .And use this cheat sheet for finding each icons string.
hope this helps.
I would like to be able to assign a xml attribute or style to a TextView that will make whatever text it has in ALL CAPITAL LETTERS.
The attributes android:inputType="textCapCharacters" and android:capitalize="characters" do nothing and look like they are for user inputed text, not a TextView.
I would like to do this so I can separate the style from the content. I know I could do this programmically but again I want keep style out of the content and the code.
I though that was a pretty reasonable request but it looks like you cant do it at this time. What a Total Failure. lol
Update
You can now use
textAllCaps
to force all caps.
What about android:textAllCaps?
By using AppCompat textAllCaps in Android Apps supporting older API's (less than 14)
There is one UI widgets that ships with AppCompat named CompatTextView is a Custom TextView extension that adds support for textAllCaps
For newer android API > 14 you can use :
android:textAllCaps="true"
A simple example:
<android.support.v7.internal.widget.CompatTextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:textAllCaps="true"/>
Source:developer.android
Update:
As it so happens CompatTextView was replaced by AppCompatTextView in
latest appcompat-v7 library ~ Eugen Pechanec
It is really very disappointing that you can't do it with styles (<item name="android:textAllCaps">true</item>) or on each XML layout file with the textAllCaps attribute, and the only way to do it is actually using theString.toUpperCase() on each of the strings when you do a textViewXXX.setText(theString).
In my case, I did not wanted to have theString.toUpperCase() everywhere in my code but to have a centralized place to do it because I had some Activities and lists items layouts with TextViews that where supposed to be capitalized all the time (a title) and other who did not... so... some people may think is an overkill, but I created my own CapitalizedTextView class extending android.widget.TextView and overrode the setText method capitalizing the text on the fly.
At least, if the design changes or I need to remove the capitalized text in future versions, I just need to change to normal TextView in the layout files.
Now, take in consideration that I did this because the App's Designer actually wanted this text (the titles) in CAPS all over the App no matter the original content capitalization, and also I had other normal TextViews where the capitalization came with the the actual content.
This is the class:
package com.realactionsoft.android.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewTreeObserver;
import android.widget.TextView;
public class CapitalizedTextView extends TextView implements ViewTreeObserver.OnPreDrawListener {
public CapitalizedTextView(Context context) {
super(context);
}
public CapitalizedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CapitalizedTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public void setText(CharSequence text, BufferType type) {
super.setText(text.toString().toUpperCase(), type);
}
}
And whenever you need to use it, just declare it with all the package in the XML layout:
<com.realactionsoft.android.widget.CapitalizedTextView
android:id="#+id/text_view_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Some will argue that the correct way to style text on a TextView is to use a SpannableString, but I think that would be even a greater overkill, not to mention more resource-consuming because you'll be instantiating another class than TextView.
I've come up with a solution which is similar with RacZo's in the fact that I've also created a subclass of TextView which handles making the text upper-case.
The difference is that instead of overriding one of the setText() methods, I've used a similar approach to what the TextView actually does on API 14+ (which is in my point of view a cleaner solution).
If you look into the source, you'll see the implementation of setAllCaps():
public void setAllCaps(boolean allCaps) {
if (allCaps) {
setTransformationMethod(new AllCapsTransformationMethod(getContext()));
} else {
setTransformationMethod(null);
}
}
The AllCapsTransformationMethod class is not (currently) public, but still, the source is also available. I've simplified that class a bit (removed the setLengthChangesAllowed() method), so the complete solution is this:
public class UpperCaseTextView extends TextView {
public UpperCaseTextView(Context context) {
super(context);
setTransformationMethod(upperCaseTransformation);
}
public UpperCaseTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setTransformationMethod(upperCaseTransformation);
}
public UpperCaseTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setTransformationMethod(upperCaseTransformation);
}
private final TransformationMethod upperCaseTransformation =
new TransformationMethod() {
private final Locale locale = getResources().getConfiguration().locale;
#Override
public CharSequence getTransformation(CharSequence source, View view) {
return source != null ? source.toString().toUpperCase(locale) : null;
}
#Override
public void onFocusChanged(View view, CharSequence sourceText,
boolean focused, int direction, Rect previouslyFocusedRect) {}
};
}
Basically, write this in TextView of XML file:
android:textAllCaps="true"
It seems like there is permission on mobile keypad setting, so the easiest way to do this is:
editText.setFilters(new InputFilter[]{new InputFilter.AllCaps()});
hope this will work
PixlUI project allows you to use textAllCaps in any textview or subclass of textview including:
Button,
EditText
AutoCompleteEditText
Checkbox
RadioButton
and several others.
You will need to create your textviews using the pixlui version rather than the ones from the android source, meaning you have to do this:
<com.neopixl.pixlui.components.textview.TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
pixlui:textAllCaps="true" />
PixlUI also allows you to set a custom typeface/font which you put in your assets folder.
I'm working on a Gradle fork of the PixlUI framework which uses gradle and allows one to specify textAllCaps as well as the typeface from styles rather than requiring them inline as the original project does.
I have already read some articles and searched on Google, but I failed to do it.
My problem is regarding the font-face.
In Android, there are only 4 attributes in "android:typeface": Normal, Sans, Serif, Monospace.
So what do I have to do to use "Verdana" in my application?
Please suggest me a correct way to use this font in my Android application.
This is a simple example... create a folder in the root of your project called assets/fonts/ then paste the TTF font file (in this case Verdana.ttf). Then, if you want to apply that font to, say a TextView, do the following:
import android.graphics.Typeface;
public class FontSampler extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
TextView tv=(TextView)findViewById(R.id.custom);
Typeface face=Typeface.createFromAsset(getAssets(),
"fonts/Verdana.ttf");
tv.setTypeface(face);
}
}
This example was taken from the ComonsWare book (written by Mark Murphy). You can download the full example from GitHub.
You can use PixlUI at https://github.com/neopixl/PixlUI
import their .jar and use it in XML
<com.neopixl.pixlui.components.textview.TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
pixlui:typeface="GearedSlab.ttf" />
Well!!
This question is pretty old but still if someone is looking for the answer(in 2015) on how to apply custom font to all the Textviews through xml code directly see below:
First:
we need to add custom font inside assets folder inside your app directory:
.ttf or .otf both work in case of Android
Second:
Create Class CustomTextView which extends TextView like below:
public class CustomTextView extends TextView {
public CustomTextView(Context context) {
super(context);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public void setTypeface(Typeface tf) {
super.setTypeface(FontCache.getFont(getContext(),"fonts/<font_name>"));
}
}
Third:
FontCache class being used inside CustomTextView's setTypeface() method.Purpose is to do basic Font Caching using HashMap:
public class FontCache {
private static Map<String,Typeface> fontMap = new HashMap<String,Typeface>();
public static Typeface getFont(Context context,String fontname){
if(fontMap.containsKey(fontname)){
return fontMap.get(fontname);
}
else{
Typeface tf = Typeface.createFromAsset(context.getAssets(),fontname);
fontMap.put(fontname,tf);
return tf;
}
}
}
Fourth:[Final step]
All we do now is use the CustomTextView directly inside our xml file wherever custom font textview is required:
<<package_name>.CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Custom Font Text"
android:textSize ="18sp"
android:textAppearance="?android:textAppearanceSmall"
android:id="#+id/custom_txt"
/>
Sorry, if this has already been posted somewhere on SO. Just thought to share if it helps someone!!
You can use simple EasyFonts third party library to set variety of custom font to your TextView. By using this library you should not have to worry about downloading and adding fonts into the assets/fonts folder. Also about Typeface object creation.
This library does not provides Verdana Font face.
But provide following font faces. Which might you would like to use.
Roboto
Droid Serif
Droid Robot
Freedom
Fun Raiser
Android Nation
Green Avocado
Recognition
Simply:
TextView myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setTypeface(EasyFonts.robotoThin(this));
I am author of this library.
To change the (custom) font of your app globally, have a look at Calligraphy
Simply add Calligraphy to your gradle.build and add the following snippet to your Application.onCreate():
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/MyCustomFont.ttf")
.setFontAttrId(R.attr.fontPath)
.build()
);
and in every Activity add the following:
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
That is all you need to do to change the font globally in your App. Have a look at the docs for more details.
// My example show you how to change fonts into a normal textView or list view
create a fonts folder into your assets dir of android and copy your custom font in that ..
assets/fonts/monaco.ttf
// Font path
String fontPath = "fonts/monaco.ttf";
// Loading Font Face
Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
// CASE 1 : Inside your list view
holder.name = (TextView) convertView
.findViewById(R.id.textView_cityName);
// set name of text in each row
holder.name.setText(CitiesNames.get(position));
// set the type of font you want to set
holder.name.setTypeface(tf);
// CASE 2 : Inside your text view
TextView tx = (TextView)findViewById(R.id.textview1);
tx.setTypeface(tf);
//vKj
TextView textView = (Textview) findViewById(R.id.mytext);
Typeface face=Typeface.createFromAsset(getAssets(),
"fonts/Verdana.ttf");
textView.setTypeFace(face);