Set custom font in Android application

Related tags

UI/UX MagicViews
Overview

MagicViews

Maven Central

Provides a simple way to set custom font in Android application.

ScreenshotsScreenshots

Adding to your project

  1. Add the library as a dependency to your build.gradle
compile 'com.ivankocijan:MagicViews:version@aar'
  1. Specify path to fonts folder in onCreate method of your Application class (See example app).
   public class MyApplication extends Application {
   
        @Override
        public void onCreate() {
            super.onCreate();
            
             MagicViews.setFontFolderPath(this, "fontFolderPath");
        
        }
   
   }
   

Usage from layout

  1. Add your application namespace to the root element in the XML xmlns:app="http://schemas.android.com/apk/res-auto"

  2. Instead of TextView use com.ivankocijan.magicviews.views.MagicTextView

    <com.ivankocijan.magicviews.views.MagicTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:typeFace="cha_chicle.otf"/>

For a complete list of features and how to use them see wiki page.

Supported views

  • TextView
  • EditText
  • Button
  • CheckBox
  • CheckedTextView
  • RadioButton
  • AutoCompleteTextView
  • MultiAutoCompleteTextView
  • PreferenceGroup
  • Preference
  • CheckboxPreference
  • SwitchPreference
  • EditTextPreference
  • Span

Supported Android versions

  • 2.3 or higher

Change log

V3.1.0

V3.0.1

  • New letter spacing attribute which lets you add horizonatal spacing between characters
  • TabLayout support - you can now set custom font on TabLayout

See wiki for more info.

You might encounter this issue after updating: /build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.0.1/res/values-v23/values-v23.xml

There are two options to fix that:

Exclude appcompact-v7 from MagicViews library:

    compile('com.ivankocijan:MagicViews:3.1.0@aar') {
        exclude group: 'com.android.support', module: 'appcompat-v7'
    }

or Compile your app with Android SDK 23:

   android {
      compileSdkVersion 23
   }

V3.0

  • Library now uses new AppCompat views which backport some cool stuff to pre-lollipop devices. See Android developer blogspot for more info
  • Added new views: RadioButton, AutoCompleteTextView and MultiAutoCompleteTextView
  • Font can now be set from code by calling setFont(String fontName) method
  • Example app is updated with new features
  • Bugfixes

Contributing

Feedback and code contributions are very much welcomed. Just make a pull request with a short description of your changes. By making contributions to this project you give permission for your code to be used under the same license.

Comments
  • Feature: MagicFontSpan

    Feature: MagicFontSpan

    MagicFontSpan gives an ability to paint CharSequence with custom typeface using MagicViews library. In very similar fashion, typeface is set with a String literal which directly corresponds to the file in assets directory.

    opened by jmarkovic 2
  • View isInEditMode

    View isInEditMode

    More often than not, when using MagicViews library, layout preview would break with an exception that font directory is empty. This is because the view tries to load the font even when in edit mode.

    This may happen if a MagicView is used in another custom view and setFont() method is called in the code of the custom view.

    Issue is avoided if all init() and setFont() methods in MagicViews are wrapped with isInEditMode() method.

    This PR introduces this change. It also adds an additional example which now demonstrates that layout preview has no issue displaying custom views.

    opened by jmarkovic 1
  • MagicEditText does not acquire text color from textAppearance attribute

    MagicEditText does not acquire text color from textAppearance attribute

    When style is set to textAppearance attribute the MagicEditText does not use the style to color text. Similar behavior is noted for EditText here: https://github.com/Prototik/HoloEverywhere/issues/730

    opened by popmir 1
  • Add spacing

    Add spacing

    Hi Ivan, it would be cool to add a feature to change space between characters, something similiar to this"

    public class SpacingTextView extends MagicTextView {
    private static final float NO_SPACING = 0.0f;
    
    private float letterSpacing = NO_SPACING;
    
    
    public SpacingTextView(Context context) {
        super(context);
        init();
    }
    
    public SpacingTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        getAttributes(attrs);
        init();
    }
    
    private void getAttributes(AttributeSet attrs) {
        if (attrs != null) {
            TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.SpacingTextView, 0, 0);
            letterSpacing = a.getFloat(R.styleable.SpacingTextView_tv_spacing, 0);
            a.recycle();
        }
    }
    
    private void init() {
        final float THRESHOLD = 0.001f;
        if (Math.abs(letterSpacing - NO_SPACING) > THRESHOLD) {
            String originalText = getText().toString();
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < originalText.length(); i++) {
                String c = "" + originalText.charAt(i);
                builder.append(c.toLowerCase());
                if (i + 1 < originalText.length()) {
                    builder.append("\u00A0");
                }
            }
    
            SpannableString finalText = new SpannableString(builder.toString();
            if (builder.toString().length() > 1) {
                for (int i = 1; i < builder.toString().length(); i += 2) {
                    finalText.setSpan(new ScaleXSpan(letterSpacing), i, i + 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                }
            }
    
            setText(finalText, TextView.BufferType.SPANNABLE);
        }
    }
    

    }

    opened by markusi7 1
  • Use the new AppCompat views which backport functionality

    Use the new AppCompat views which backport functionality

    As per this blog post: http://android-developers.blogspot.com/2015/04/android-support-library-221.html

    There are new views which backport some cool stuff to pre-lollipop devices:

    • AppCompatAutoCompleteTextView
    • AppCompatButton
    • AppCompatCheckBox
    • AppCompatCheckedTextView
    • AppCompatEditText
    • AppCompatMultiAutoCompleteTextView
    • AppCompatRadioButton
    • AppCompatRatingBar
    • AppCompatSpinner
    • AppCompatTextView

    We should extend these for a future MagicViews release.

    opened by reisub 1
  • Remove static Context reference

    Remove static Context reference

    The MagicFont utility class now contains a static reference to the context. This should be avoided as it can prevent the garbage collection of heavyweight objects, like activities or services.

    opened by martyglaubitz 1
  • typeface already defined v1.0.3

    typeface already defined v1.0.3

    When using as gradle dependency in AS 0.9.2 error is shown when compiling: Typeface already defined - I don't have any custom attribute named typeface in the project - possible that it clashes with v7 or v4 compat lib?

    opened by kjurkovic 1
  • Create attribute to enter complete font path

    Create attribute to enter complete font path

    The library starts by finding every font in the assets folder. When there's a lot of file in the folder, this leads to unacceptable lag. It simply can't be used in some cases. There should be a way to disable finding every font in the assets folder and using a path to the font instead.

    opened by 0xjohnnycage 1
  • Give access to

    Give access to "fontStyle" attribute

    fontStyle should be accessible by either a getter or by being protected. I am extending MagicEditText to override the setError method so I can use the custom type face on that one also. However the font to use is in fontStyle.

    I tried using FontUtils.getPrefFontStyle(context, attrs, PreferenceType.EDIT_TEXT_PREFERENCE); in the constructor, but for a reason I don't know after calling the super constructor, this method always returns null. I guess attrs gets modified along the way...

    opened by 0xjohnnycage 1
  • MagicTextView does not work in IDE (Android Studio)

    MagicTextView does not work in IDE (Android Studio)

    MagicTextView cannot be shown in the IDE because of the following exception:

    java.lang.UnsupportedClassVersionError: com/ivankocijan/magicviews/views/MagicTextView : Unsupported major.minor version 51.0
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClassCond(ClassLoader.java:637)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:471)
        at com.intellij.util.lang.UrlClassLoader._defineClass(UrlClassLoader.java:189)
        at com.intellij.util.lang.UrlClassLoader.defineClass(UrlClassLoader.java:185)
        at com.intellij.util.lang.UrlClassLoader.findClass(UrlClassLoader.java:146)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
        at com.android.tools.idea.rendering.RenderClassLoader.loadClassFromJar(RenderClassLoader.java:76)
        at org.jetbrains.android.uipreview.ProjectClassLoader.loadClassFromModuleOrDependency(ProjectClassLoader.java:106)
        at org.jetbrains.android.uipreview.ProjectClassLoader.load(ProjectClassLoader.java:87)
        at com.android.tools.idea.rendering.RenderClassLoader.findClass(RenderClassLoader.java:54)
        at org.jetbrains.android.uipreview.ProjectClassLoader.findClass(ProjectClassLoader.java:54)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
        at org.jetbrains.android.uipreview.ViewLoader.loadClass(ViewLoader.java:174)
        at org.jetbrains.android.uipreview.ViewLoader.loadView(ViewLoader.java:97)
        at com.android.tools.idea.rendering.LayoutlibCallback.loadView(LayoutlibCallback.java:172)
        at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:207)
        at android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:135)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:469)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:373)
        at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:399)
        at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:336)
        at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:332)
        at com.android.tools.idea.rendering.RenderService$3.compute(RenderService.java:558)
        at com.android.tools.idea.rendering.RenderService$3.compute(RenderService.java:547)
        at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:932)
        at com.android.tools.idea.rendering.RenderService.createRenderSession(RenderService.java:547)
        at com.android.tools.idea.rendering.RenderService.render(RenderService.java:674)
        at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager.doRender(AndroidLayoutPreviewToolWindowManager.java:586)
        at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager.access$1900(AndroidLayoutPreviewToolWindowManager.java:80)
        at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager$6$1.run(AndroidLayoutPreviewToolWindowManager.java:528)
        at com.intellij.openapi.progress.impl.ProgressManagerImpl$2.run(ProgressManagerImpl.java:178)
        at com.intellij.openapi.progress.ProgressManager.executeProcessUnderProgress(ProgressManager.java:209)
        at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:212)
        at com.intellij.openapi.progress.impl.ProgressManagerImpl.runProcess(ProgressManagerImpl.java:171)
        at org.jetbrains.android.uipreview.AndroidLayoutPreviewToolWindowManager$6.run(AndroidLayoutPreviewToolWindowManager.java:523)
        at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:320)
        at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:310)
        at com.intellij.util.ui.update.MergingUpdateQueue$2.run(MergingUpdateQueue.java:254)
        at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:269)
        at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:227)
        at com.intellij.util.ui.update.MergingUpdateQueue.run(MergingUpdateQueue.java:217)
        at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:238)
        at com.intellij.util.Alarm$Request$1.run(Alarm.java:327)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
        at java.util.concurrent.FutureTask.run(FutureTask.java:138)
        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
        at java.lang.Thread.run(Thread.java:695)
    
    opened by 0xjohnnycage 1
  • AllowBackup value in Manifest

    AllowBackup value in Manifest

    "allowBackup:true" code block is automatically generated by Android Studio - libraries should have this value set to false in order to avoid failures with manifest merger.

    opened by zplesac 0
  • NoSuchMethodError: Landroid/text/TextPaint;.<init>

    NoSuchMethodError: Landroid/text/TextPaint;.

    Crashlytics report from production on MagicViews version 3.0.0. (device Huawei G610 U00): Report

    Init of the view method (error occurred on line 3): Init

    XML layout: Layout

    opened by igortepavac 0
  • Under-the-hood refactoring

    Under-the-hood refactoring

    While introducing the last PR ( #29 ), I've noticed that some classes keep a reference to the Context. This may be an undesirable since it only might be useful for initialisation.

    I propose that the part that initialises typefaces is moved to MagicViews class and that MagicFonts remains the point where typefaces live and keep their references without any Context reference.

    I'm willing to do this work, but would need to discuss every change as this may be a major release (if we choose to remove deprecated methods). Would you like future PRs to go to development branch or a new branch just for this?

    opened by jmarkovic 0
Owner
Ivan Kocijan
Ivan Kocijan
A set of Android-UI components to make it easier to request permission in a user friendly way.

Permission UI A set of Android-UI components to make it easier to request permission in a user friendly way. Access background location A jetpack comp

Stefan Wärting 54 Nov 3, 2022
A set of widgets to create smooth slideshows with ease.

Android SlideShow Widget A set of widgets to create smooth slide shows with ease. The slide show components are fully customizable and are not limited

MarvinLabs 211 Nov 20, 2022
Useful library to use custom fonts in your android app

EasyFonts A simple and useful android library to use custom fonts in android apps without adding fonts into asset/resource folder.Also by using this l

Vijay Vankhede 419 Sep 9, 2022
Custom android music player view.

InteractivePlayerView Custom android music player view. Screen Check it on youtube Usage(XML) Define it in your xml file. <co.mobiwise.library.Intera

Mert Şimşek 744 Dec 25, 2022
Android Library for Custom Switches.

Android Library for Custom Switches.

Angad Singh 376 Jan 4, 2023
Custom wheel widget for android

Wheel widget for Android To include the wheel widget in the current layout, you should add in the layout xml this lines: <it.sephiroth.android

Alessandro Crugnola 384 Nov 21, 2022
IconicDroid is a custom Android Drawable which allows to draw icons from several iconic fonts.

IconicDroid IconicDroid is a custom Android Drawable which allows to draw icons from several iconic fonts. Try out the sample application on the Googl

Artur Termenji 387 Nov 20, 2022
A beautiful Android custom View that works similar to a range or seekbar. With animations.

ValueBar A beautiful Android custom View that works similar to a range or seekbar. Selection by gesture. With animations. Supporting API level 11+. De

Philipp Jahoda 147 Nov 20, 2022
An android custom view that displays a circle with a colored arc given a mark

MarkView An android custom view that displays a circle with a colored arc given a mark. Usage Add as a dependency compile 'com.github.xiprox.markv

İhsan Işık 200 Nov 25, 2022
Custom UI control for android which is showing data as a segments and a value inside them.

Segmented Bar View for Android Custom UI control for android which is showing data as a segments and a value inside them. Screenshots Install From rep

GSPD 354 Nov 10, 2022
This is a android custom view , like a scratch card effect!

ScratchView This is a android custom view , like a scratch card effect! Last Update 采纳DearZack童鞋的优化思路,把计算擦除面积比例的操作放在手指离开屏幕时,以降低对CPU的占用。 Articles Scrat

D_clock爱吃葱花 316 Nov 29, 2022
An Android custom view to display digits rendered as dots in a grid, with a style like a 1970s LED clock.

#DotMatrixView This is an Android library project providing a custom view that can display things on a grid of dots. When the displayed value changes,

Mark Roberts 48 Apr 21, 2022
NumberPickerView - Custom Android View to provide a user friendly way of picking numbers. 🧪

?? Custom view for Android which provides a modern design and gestures for picking numbers in a user friendly way.

Mirkamal 6 Feb 16, 2022
Android Custom CountDownView

Android Custom CountDownView

the Sun. 4 Dec 11, 2022
(Deprecated) A custom view component that mimics the new Material Design Bottom Navigation pattern.

BottomBar (Deprecated) I don't have time to maintain this anymore. I basically wrote the whole library in a rush, without tests, while being a serious

Iiro Krankka 8.4k Dec 29, 2022
a custom view that provides dragged and scaled

DragScaleCircleView A custom imageview that provides the circle window can be dragged and scaled, crop image. How does it look? Why? Sometimes need to

null 514 Dec 22, 2022
Custom & highly configurable seek slider with sliding intervals, disabled state and every possible setting to tackle!

LabeledSeekSlider Custom & highly configurable seek slider with sliding intervals, disabled state and every possible setting to tackle! Minimum target

Edgar Žigis 78 Sep 27, 2022
A custom liquidbounce for redesky.com

FDPClient A free mixin-based injection hacked-client for Minecraft using Minecraft Forge based on LiquidBounce. Website: https://fdp.liulihaocai.pw/ L

null 69 Dec 26, 2022
Sliders for compose with custom styles

Custom compose sliders This package allows you to build highly customizable sliders and tracks for compose for android Add to your project Add it in y

Vladislav Krot 52 Dec 15, 2022