Android Open Source - android_font_widgets Font






From Project

Back to project page android_font_widgets.

License

The source code is released under:

[Apache License](http://www.apache.org/licenses/): Version 2.0, January 2004 =============== ## TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION ## ### 1. Definitions. ### "License" sha...

If you think the Android project android_font_widgets listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/*
 * =================================================================================================
 *                 Copyright (C) 2012 - 2014 Martin Albedinsky [Wolf-ITechnologies]
 * =================================================================================================
 *         Licensed under the Apache License, Version 2.0 or later (further "License" only).
 * -------------------------------------------------------------------------------------------------
 * You may use this file only in compliance with the License. More details and copy of this License
 * you may obtain at//from   w w  w  .  j  ava2  s . c  om
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * You can redistribute, modify or publish any part of the code written within this file but as it
 * is described in the License, the software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES or CONDITIONS OF ANY KIND.
 *
 * See the License for the specific language governing permissions and limitations under the License.
 * =================================================================================================
 */
package com.wit.android.ui.widget.font;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;

import java.io.File;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <h3>Class Overview</h3>
 * Simple wrapper for {@link android.graphics.Typeface} used by {@link FontApplier}
 * to simplify using of custom fonts within an Android application.
 * <p>
 * <b>Note</b>, that all fonts used by this API must be placed within an assets folder in folder
 * {@link #FONT_FOLDER}.
 *
 * @author Martin Albedinsky
 */
public final class Font {

  /**
   * Interface ===================================================================================
   */

  /**
   * Constants ===================================================================================
   */

  /**
   * Log TAG.
   */
  private static final String TAG = "Font";

  /**
   * Flag indicating whether the debug output trough log-cat is enabled or not.
   */
  private static final boolean DEBUG_ENABLED = FontWidgetsConfig.LIBRARY_DEBUG_LOG_ENABLED;

  /**
   * Flag indicating whether the output trough log-cat is enabled or not.
   */
  // private static final boolean LOG_ENABLED = true;

  /**
   * Suffix for original <b>true Typeface</b> fonts.
   */
  public static final String TTF_SUFFIX = ".ttf";

  /**
   * Sub-folder within an application assets folder, where must be placed all custom fonts.
   * Can also contain custom sub-folders to group fonts.
   * <p>
   * Constant value: <b>font/</b>
   */
  public static final String FONT_FOLDER = "font" + File.separator;

  /**
   * Static members ==============================================================================
   */

  /**
   * Matcher for <b>.ttf</b> file suffix.
   */
  private static final Matcher TTF_SUFFIX_MATCHER = Pattern.compile("(.*)\\.ttf").matcher("");

  /**
   * Cache of used fonts.
   */
  private static final HashMap<String, Font> CACHE = new HashMap<>();

  /**
   * Members =====================================================================================
   */

  /**
   * Typeface for this font.
   */
  private Typeface mTypeFace;

  /**
   * Path to the .ttf file within an application assets folder, which should be represented by this
   * font. This path also contain a style suffix (_bold, _italic, _bold_italic).
   */
  private final String mFontPath;

  /**
   * Like {@link #mFontPath} but this path is without style suffix.
   */
  private final String mRawFontPath;

  /**
   * Constructors ================================================================================
   */

  /**
   * Creates a new instance of Font with the specified path to font file within assets folder.
   * <b>Note, that empty path or {@code null} are not valid attributes.</b>
   * <p>
   * <b>Only .ttf font is allowed!</b>
   *
   * @param fontPath  Relative path to the .ttf file (with or without .ttf suffix) placed within
   *                  an application assets folder (within {@link #FONT_FOLDER} folder) which will
   *                  be represented by this newly created Font instance.
   * @param textStyle One of {@link android.graphics.Typeface#NORMAL}, {@link android.graphics.Typeface#BOLD}, {@link android.graphics.Typeface#ITALIC},
   *                  {@link android.graphics.Typeface#BOLD_ITALIC}.
   * @throws IllegalArgumentException If the given <var>fontPath</var> is empty.
   */
  public Font(@NonNull String fontPath, @TypefaceStyle.TextStyle int textStyle) {
    if (TextUtils.isEmpty(fontPath)) {
      throw new IllegalArgumentException("Font path cannot be empty!");
    }
    if (!TTF_SUFFIX_MATCHER.reset(fontPath).matches()) {
      fontPath = FONT_FOLDER + fontPath + TTF_SUFFIX;
    } else {
      fontPath = FONT_FOLDER + fontPath;
    }
    this.mFontPath = TypefaceStyle.resolve(textStyle).correctFontPath(mRawFontPath = fontPath);
  }

  /**
   * Methods =====================================================================================
   */

  /**
   * Public --------------------------------------------------------------------------------------
   */

  /**
   * Same as {@link #create(String, int)} with {@link android.graphics.Typeface#NORMAL} as text style.
   *
   * @return New or cached instance of Font.
   * @see #create(android.content.Context, android.util.AttributeSet, int)
   * @see #create(android.content.Context, int)
   */
  public static Font create(@NonNull String fontPath) {
    return create(fontPath, Typeface.NORMAL);
  }

  /**
   * Creates a new instance of Font with the given font path and text style.
   * <p>
   * See {@link #Font(String, int)} for more info about attributes for Font.
   *
   * @return New or cached instance of Font for the given path and text style.
   * @see #create(android.content.Context, android.util.AttributeSet, int)
   * @see #create(android.content.Context, int)
   * @see #create(String)
   */
  public static Font create(@NonNull String fontPath, @TypefaceStyle.TextStyle int textStyle) {
    final Font font = new Font(fontPath, textStyle);
    if (CACHE.containsKey(font.mFontPath)) {
      if (DEBUG_ENABLED) {
        Log.v(TAG, "Re-using cached font for path(" + font.mFontPath + ").");
      }
      return CACHE.get(font.mFontPath);
    }
    if (DEBUG_ENABLED) {
      Log.v(TAG, "Caching new font for path(" + font.mFontPath + ").");
    }
    CACHE.put(font.mFontPath, font);
    return font;
  }

  /**
   * Creates a new instance of Font with the font path obtained from the given <var>attrs</var>.
   * <p>
   * See {@link #Font(String, int)} for more info about attributes for Font.
   *
   * @param context  Valid context used to process the given attributes set.
   * @param attrs    Attributes set which should contain {@link R.styleable#Ui_Widget_uiFontPath ui:uiFontPath}
   *                 attribute parsed from xml file.
   * @param defStyle An attribute of the default style presented within the current theme which
   *                 supplies default attributes for {@link android.content.res.TypedArray}.
   * @return New or cached instance of Font or {@code null} if a theme of the given <var>context</var>
   * is invalid.
   * @see #create(String)
   * @see #create(android.content.Context, int)
   */
  @Nullable
  public static Font create(@NonNull Context context, @NonNull AttributeSet attrs, int defStyle) {
    final Resources.Theme theme = context.getTheme();
    return theme != null ? create(
        theme.obtainStyledAttributes(attrs, new int[]{R.attr.uiFontPath}, defStyle, 0),
        TypefaceStyle.obtainTextStyle(context, attrs)
    ) : null;
  }

  /**
   * Creates a new instance of Font with the font path obtained from the given <var>style</var>.
   * <p>
   * See {@link #Font(String, int)} for more info about attributes for Font.
   *
   * @param context Valid context used to process the given style.
   * @param style   A resource id of the style which should contain {@link R.styleable#Ui_Widget_uiFontPath ui:uiFontPath}
   *                attribute.
   * @return New or cached instance of Font or {@code null} if a theme of the given <var>context</var>
   * is invalid.
   * @see #create(String)
   * @see #create(android.content.Context, android.util.AttributeSet, int)
   */
  @Nullable
  public static Font create(@NonNull Context context, int style) {
    final Resources.Theme theme = context.getTheme();
    return theme != null ? create(
        theme.obtainStyledAttributes(style, new int[]{R.attr.uiFontPath}),
        TypefaceStyle.obtainTextStyle(context, style)
    ) : null;
  }

  /**
   * Creates a new instance of Font with the font path obtained from the {@code 0} index of the
   * passed <var>typedArray</var>.
   *
   * @param typedArray An instance of typed array to obtain font path from.
   * @param textStyle  Text style flag to properly create instance of Font.
   * @return New or cached instance of Font.
   */
  private static Font create(TypedArray typedArray, int textStyle) {
    if (typedArray != null) {
      final String fontPath = typedArray.getString(0);
      typedArray.recycle();
      return !TextUtils.isEmpty(fontPath) ? Font.create(fontPath, textStyle) : null;
    }
    return null;
  }

  /**
   * Getters + Setters ---------------------------------------------------------------------------
   */

  /**
   * Returns an instance of the Typeface which is created for the .ttf file placed within an application
   * assets folder under the current font path.
   * <p>
   * See {@link android.graphics.Typeface#createFromAsset(android.content.res.AssetManager, String)} for more info.
   *
   * @param context Valid context used to create requested TypeFace.
   * @return Instance of the requested Typeface.
   */
  @NonNull
  public Typeface obtainTypeface(@NonNull Context context) {
    return (mTypeFace == null) ? (mTypeFace = this.createTypeface(context)) : mTypeFace;
  }

  /**
   * Returns the current font path of this Font instance.
   * <p>
   * <b>Note</b>, that this path also contains a suffix of style passed to {@link #Font(String, int)}
   * constructor. See {@link TypefaceStyle#correctFontPath(String)} for more info.
   *
   * @return Full path to the .ttf file within an application assets folder.
   * @see #obtainTypeface(android.content.Context)
   */
  @NonNull
  public String getFontPath() {
    return mFontPath;
  }

  /**
   * Protected -----------------------------------------------------------------------------------
   */

  /**
   * Private -------------------------------------------------------------------------------------
   */

  /**
   * Creates a new instance of Typeface from the current font path. If creating of typeface form
   * the current {@link #mFontPath} fails, the raw {@link #mFontPath} will be used to create
   * type face.
   *
   * @param context Valid context used to create requested TypeFace.
   * @return Typeface instance.
   */
  private Typeface createTypeface(Context context) {
    Typeface typeface = null;
    // First try to create from the styled font path.
    try {
      typeface = Typeface.createFromAsset(context.getAssets(), mFontPath);
    } catch (Exception ignored) {
      Log.e(TAG, "Type face with path('" + mFontPath + "') not found within assets folder. Trying to create from raw font path(" + mRawFontPath + ").");
    }

    if (typeface == null) {
      // Create from raw path.
      try {
        typeface = Typeface.createFromAsset(context.getAssets(), mRawFontPath);
      } catch (Exception e) {
        throw new RuntimeException("Type face with path('" + mRawFontPath + "') not found within assets folder or isn't valid '.ttf' file.", e);
      }
    }
    return typeface;
  }

  /**
   * Inner classes ===============================================================================
   */
}




Java Source Code List

com.wit.android.ui.widget.font.FontApplier.java
com.wit.android.ui.widget.font.FontAutoCompleteTextView.java
com.wit.android.ui.widget.font.FontButton.java
com.wit.android.ui.widget.font.FontCheckBox.java
com.wit.android.ui.widget.font.FontEditText.java
com.wit.android.ui.widget.font.FontRadioButton.java
com.wit.android.ui.widget.font.FontTextView.java
com.wit.android.ui.widget.font.FontWidgetsConfig.java
com.wit.android.ui.widget.font.Font.java
com.wit.android.ui.widget.font.TypefaceStyle.java