How to apply font to whole application? - android

Everyone
I want to apply my custom font to whole application not just a textview or not for an activity. if it is possible make just change in manifest file so it is easy for me.
so help me out.

You can create custom textview class and use that class whenever you need to use custom fonts.
Check this link: How to make a custom TextView?

There's also a library that does this. Very simple to use and set up.
https://github.com/chrisjenx/Calligraphy

Try this method for all activity. Or you can make this method in you utility class and use in you activity class see bellow.
Method in your utility.java file.
public static void setFont(ViewGroup group, Typeface font) {
int count = group.getChildCount();
View v;
for (int i = 0; i < count; i++) {
v = group.getChildAt(i);
if (v instanceof TextView || v instanceof EditText
|| v instanceof Button) {
((TextView) v).setTypeface(font);
} else if (v instanceof ViewGroup)
setFont((ViewGroup) v, font);
}
}
And then in your Activity.java file.
ll_Homescreen = (LinearLayout) findViewById(R.id.ll_Homescreen);
FontStyle = Typeface.createFromAsset(getAssets(), path of you font);
utility.setFont(ll_Homescreen, FontStyle);
I hope this will help you Happy Coding.

Related

Is there a way to set font style for the entire app

I'm trying to apply a custom font style for my app..I know:
Typeface tf = Typeface.createFromAsset(getAssets(),"font.ttf");
text.setTypeface(tf);
But I want to apply custom font style for the entire app including the action bar tabs and all the text view.
is there a "supper" way to apply a custom font for the whole app??
You cannot set a custom font for the whole application in a single point yet, but you have to set the typeface for every view by yourself.
See this answer: Android: Want to set custom fonts for whole application not runtime
Custom ActionBar Styling
ActionBar Tabs
ActionBar Title
There is no way to set an entire applications typeface, but if you are looking for a more general programatic solution, I created a static class that can be used to set the Typeface of an entire view (Activity UI). Note that I am working with Mono (C#) but you can implement it easily using Java.
You can pass this class a layout or a specific view that you want to customize. If you want to be super efficient you could implement it using the Singleton pattern.
public static class AndroidTypefaceUtility
{
static AndroidTypefaceUtility()
{
}
//Refer to the code block beneath this one, to see how to create a typeface.
public static void SetTypefaceOfView(View view, Typeface customTypeface)
{
if (customTypeface != null && view != null)
{
try
{
if (view is TextView)
(view as TextView).Typeface = customTypeface;
else if (view is Button)
(view as Button).Typeface = customTypeface;
else if (view is EditText)
(view as EditText).Typeface = customTypeface;
else if (view is ViewGroup)
SetTypefaceOfViewGroup((view as ViewGroup), customTypeface);
else
Console.Error.WriteLine("AndroidTypefaceUtility: {0} is type of {1} and does not have a typeface property", view.Id, typeof(View));
}
catch (Exception ex)
{
Console.Error.WriteLine("AndroidTypefaceUtility threw:\n{0}\n{1}", ex.GetType(), ex.StackTrace);
throw ex;
}
}
else
{
Console.Error.WriteLine("AndroidTypefaceUtility: customTypeface / view parameter should not be null");
}
}
public static void SetTypefaceOfViewGroup(ViewGroup layout, Typeface customTypeface)
{
if (customTypeface != null && layout != null)
{
for (int i = 0; i < layout.ChildCount; i++)
{
SetTypefaceOfView(layout.GetChildAt(i), customTypeface);
}
}
else
{
Console.Error.WriteLine("AndroidTypefaceUtility: customTypeface / layout parameter should not be null");
}
}
}
In your activity you will need to create a Typeface object. I create mine in the OnCreate() using a .ttf file placed in my Resources/Assets/ directory. Make sure that the file is marked as an Android Asset in its' properties.
protected override void OnCreate(Bundle bundle)
{
...
LinearLayout rootLayout = (LinearLayout)FindViewById<LinearLayout>(Resource.Id.signInView_LinearLayout);
Typeface allerTypeface = Typeface.CreateFromAsset(base.Assets,"Aller_Rg.ttf");
AndroidTypefaceUtility.SetTypefaceOfViewGroup(rootLayout, allerTypeface);
}

Custom font in android project

I am trying to assign a different font to my project.
I want the new font is valid for the entire project, but all I find is to change the font to a textview
Typeface font1 = Typeface.createFromAsset(getAssets(), "fonts/RockFont.ttf");
TextView customText1 = (TextView)findViewById(R.id.text1);
customText1.setTypeface(font1);
customText1.setTextSize(40.f);
customText1.setText("Hello! This is a custom font...");
There any way to default to the entire project a custom font?
Best regard
Not exactly what you asked for, but building on the comment above there are ways to make using a custom font with default controls easier.
This shows how to extend TextView and use a custom attribute so the TextView supports a custom font.
Custom fonts and XML layouts (Android)
What I do is create a support class and instantiate it from my activity and pass through all the views I wish to style.
public class textfactory{
private TextView tv;
private Button b;
private RadioButton rb;
private TypeFace font;
/**
* fetch font resource
*/
public textfactory(Context context){
this.font = Typeface.createFromAsset(context.getAssets(), 'customfont.ttf');
}
/**
* pass in all the views you wish to apply font to
*/
public void style(View... views){
for(View v : views){
if(v instance of TextView)
{
tv = (TextView)v;
tv.setTypeface(this.font);
}
else if(v instance of Button)
{
b = (Button)v;
b.setTypeface(this.font);
}
else if(v instance of RadioButton)
{
rb = (RadioButton)v;
rb.setTypeface(this.font);
}
//add as many view conditionals as required
}
}
}

ActionBarSherlock (ABS): how to customize the text of action mode close item?

I'm using ABS vers. 4 and I need to simply change the default "Done" text that is displayed besides the action mode close icon, but I really can't figure out how to do it.
I think that text needs to be customizable for at least two good reasons:
"Done" is not appropriate for all contexts (e.g. "Cancel" could be more appropriate, and I've seen some apps, such as the "My Files" app on Galaxy Tab, use it)
"Done" needs to be localized according to the user's language
Is it possible to do customize that text? If so can anyone tell me how to do it?
Thanks in advance.
EDIT
I've found a temporary workaround, that I post in the following:
private TextView getActionModeCloseTextView() {
// ABS 4.0 defines action mode close button text only for "large" layouts
if ((getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) ==
Configuration.SCREENLAYOUT_SIZE_LARGE)
{
// retrieves the LinearLayout containing the action mode close button text
LinearLayout action_mode_close_button =
(LinearLayout) getActivity().findViewById(R.id.abs__action_mode_close_button);
// if found, returns its last child
// (in ABS 4.0 there is no other way to refer to it,
// since it doesn't have an id nor a tag)
if (action_mode_close_button != null) return (TextView)
action_mode_close_button.getChildAt(action_mode_close_button.getChildCount() - 1);
}
return null;
}
That's the method I came up with. Please NOTE that it does heavily rely upon the structure of the abs__action_mode_close_item.xml of ABS 4.0.
This works for my scenario, but, as you can see, it cannot be considered sufficiently satisfying to promote it to a real "answer", that's why I only edited my previous post.
Hope that helps someone else, but I also hope that someone could share a better and cleaner solution.
You can use a theme to override the default icon:
<item name="actionModeCloseDrawable">#drawable/navigation_back</item>
<item name="android:actionModeCloseDrawable">#drawable/navigation_back</item>
I edited the code from PacificSky to be able to customize the color and font size of the close button, both in pre ICS and >ICS.
I created a method named customizeActionModeCloseButton
private void customizeActionModeCloseButton() {
int buttonId = Resources.getSystem().getIdentifier("action_mode_close_button", "id", "android");
View v = getGSActivity().findViewById(buttonId);
if (v == null) {
buttonId = R.id.abs__action_mode_close_button;
v = getGSActivity().findViewById(buttonId);
}
if (v == null)
return;
LinearLayout ll = (LinearLayout) v;
if (ll.getChildCount() > 1 && ll.getChildAt(1) != null) {
TextView tv = (TextView) ll.getChildAt(1);
tv.setText(R.string.close_action_mode);
tv.setTextColor(getResources().getColor(R.color.white));
tv.setTextSize(18);
}
}
and I call it just after calling startActionMode()
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
actionMode = getActivity().startActionMode(this);
customizeActionModeCloseButton();
return true;
}
It's been a while, but here's a slightly less hacky solution - putting it out there for posterity.
For Android versions < ICS
Put the following line in your application's strings.xml:
<string name="abs__action_mode_done">Cancel</string>
This overrides the TextView's (defined in ActionBarSherlock/res/layout-large/abs__action_mode_close_item.xml) android:text attribute.
For Android versions ICS and above
The native ActionBar functionality is used on ICS and up. You need to find and override the string associated with the done button, using the following code:
int buttonId = Resources.getSystem().getIdentifier("action_mode_close_button", "id", "android");
if (buttonId != 0)
{
View v = findViewById(buttonId);
if (v != null)
{
LinearLayout ll = (LinearLayout)v;
View child = ll.getChildAt(1);
if (child != null)
{
TextView tv = (TextView)child;
tv.setText(R.string.cancel);
}
}
}
Thanks for PacificSky's answer. It's useful for my case.
Something needs to be explained here is that findViewById(buttonId) might return null in some cases such as called in onCreateActionMode() function, because the LinearLayout for ActionMode close button not yet initialized at that time I guess.
I want to hide the action mode close button, so i just sendEmptyMessageDelayed in onCreateActionMode() and call PacificSky's 200ms later. It works for me.
Here is my approach with Java code:
private void customizeActionModeCloseButton(String title, int iconID) {
int buttonId = Resources.getSystem().getIdentifier("action_mode_close_button", "id", "android");
View v = findViewById(buttonId);
if (v == null) {
buttonId = R.id.abs__action_mode_close_button;
v = findViewById(buttonId);
}
if (v == null)
return;
LinearLayout ll = (LinearLayout) v;
if (ll.getChildCount() > 1 && ll.getChildAt(1) != null) {
//custom icon
ImageView img = (ImageView) ll.getChildAt(0);
img.setImageResource(iconID);
//custom text
TextView tv = (TextView) ll.getChildAt(1);
tv.setText(title);
tv.setTextColor(Color.WHITE);
}
}
com.actionbarsherlock.view.ActionMode contains method:
setTitle
It is used to change text near Close Icon in the ActionBar.
ActionMode is available in your com.actionbarsherlock.view.ActionMode.Callback interface implementation methods, like onCreateActionMode.
What you can do - is save incoming ActionMode reference and use it later to change title as your like. Or, if it is not dynamic - you can setup at with your constant in onCreateActionMode.

Easiest way to globally change Android font?

I have a ttf file, and its theoretically possible, but I'm not looking to touch over 500 different lines of code to programmatically change this. What is the easiest way?
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/graphics/Typefaces.html
To extend previous answer with static TYPEFACE:
Add new function:
public static void applyCustomFont(ViewGroup list, Typeface customTypeface) {
for (int i = 0; i < list.getChildCount(); i++) {
View view = list.getChildAt(i);
if (view instanceof ViewGroup) {
applyCustomFont((ViewGroup) view, customTypeface);
} else if (view instanceof TextView) {
((TextView) view).setTypeface(customTypeface);
}
}
}
Get root view of our Layout:
View rootView = findViewById(android.R.id.content)
Than apply custom font for whole activity form with all sub-elements:
applyCustomFont((ViewGroup)rootView, C.TYPEFACE.ArialRounded(this));
I've dealt with this problem myself; although I couldn't set a custom font globally, I was able to just make it little easier to deal with.
So in my Constants class (C.java) I have an Inner class:
public static final class TYPEFACE {
public static final Typeface Helvetica(Context ctx){
Typeface typeface = Typeface.createFromAsset(ctx.getAssets(), "helvetica.otf");
return typeface;
}
public static final Typeface ArialRounded(Context ctx){
Typeface typeface = Typeface.createFromAsset(ctx.getAssets(), "arial_rounded.ttf");
return typeface;
}
}
And in my code, after declaring and intializing the TextView I just set it's Typeface:
TextView title = (TextView)findViewById(R.id.title);
title.setTypeface(C.TYPEFACE.Helvetica(this));
I know this doesn't solve your problem but I hope it helps...
-serkan
Another way to go would be a custom view extending TextView. Not pretty, but you wouldn't need to copy the font code all over the place.
In all, its a pretty annoying problem for sure.

How to iterate through a view's elements

I have a view with radios, inputs and a button and when I click it, I want to check that all inputs contain information. How can I iterate through the view's elements in the activity and check if every textview meets the aforementioned requirement ? Thanks.
I've done something similar in some code I don't have with me at the moment, but from memory it should be something like this (assuming a parent view LinearLayout with an id of "layout"):
LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
boolean success = formIsValid(layout);
public boolean formIsValid(LinearLayout layout) {
for (int i = 0; i < layout.getChildCount(); i++) {
View v = layout.getChildAt(i);
if (v instanceof EditText) {
//validate your EditText here
} else if (v instanceof RadioButton) {
//validate RadioButton
} //etc. If it fails anywhere, just return false.
}
return true;
}
To apply the method by kcoppock recursively, you can change it to this:
private void loopViews(ViewGroup view) {
for (int i = 0; i < view.getChildCount(); i++) {
View v = view.getChildAt(i);
if (v instanceof EditText) {
// Do something
} else if (v instanceof ViewGroup) {
this.loopViews((ViewGroup) v);
}
}
}
If you are writing in Kotlin, Android Jetpack's Kotlin extensions (KTX) provide extension functions for iterating over a ViewGroup's children.
myViewGroup.forEach { ... }
myViewGroup.forEachIndexed { index, view -> ... }
Just add the dependency to your app. Check the link above to get the most up-to-date version.
implementation "androidx.core:core-ktx:1.2.0"
These extensions contains hoards of useful functions otherwise chalked up as boilerplate. Worth checking out now to save time in the future!
Your onClickListener supplies the View v object; use View rV = v.getRootView() to position yourself on the form. Then use rV.findViewWithTag( ... ) or rV.findViewByID(R.id. ... ) to locate your form elements.

Categories

Resources