Repository: chrisjenx/Calligraphy
Branch: master
Commit: 085e441954d7
Files: 49
Total size: 119.9 KB
Directory structure:
gitextract_ddbcg5tt/
├── .gitignore
├── CHANGELOG.md
├── CalligraphySample/
│ ├── .gitignore
│ ├── build.gradle
│ ├── proguard-rules.txt
│ └── src/
│ └── main/
│ ├── AndroidManifest.xml
│ ├── java/
│ │ └── uk/
│ │ └── co/
│ │ └── chrisjenx/
│ │ └── calligraphy/
│ │ └── sample/
│ │ ├── CalligraphyApplication.java
│ │ ├── CustomTextView.java
│ │ ├── CustomViewWithTypefaceSupport.java
│ │ ├── MainActivity.java
│ │ ├── PlaceholderFragment.java
│ │ └── TextField.java
│ └── res/
│ ├── layout/
│ │ ├── activity_main.xml
│ │ ├── fragment_main.xml
│ │ ├── stub.xml
│ │ └── stub_with_font_path.xml
│ ├── values/
│ │ ├── attrs.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── values-w820dp/
│ └── dimens.xml
├── LICENSE
├── README.md
├── build.gradle
├── calligraphy/
│ ├── .gitignore
│ ├── build.gradle
│ ├── consumer-proguard-rules.txt
│ ├── gradle.properties
│ └── src/
│ └── main/
│ ├── AndroidManifest.xml
│ ├── java/
│ │ └── uk/
│ │ └── co/
│ │ └── chrisjenx/
│ │ └── calligraphy/
│ │ ├── CalligraphyActivityFactory.java
│ │ ├── CalligraphyConfig.java
│ │ ├── CalligraphyContextWrapper.java
│ │ ├── CalligraphyFactory.java
│ │ ├── CalligraphyLayoutInflater.java
│ │ ├── CalligraphyTypefaceSpan.java
│ │ ├── CalligraphyUtils.java
│ │ ├── HasTypeface.java
│ │ ├── ReflectionUtils.java
│ │ └── TypefaceUtils.java
│ └── res/
│ └── values/
│ ├── attrs.xml
│ ├── ids.xml
│ └── public.xml
├── gradle/
│ ├── deploy.gradle
│ └── wrapper/
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# built application files
*.apk
*.ap_
# files for the dex VM
*.dex
# Java class files
*.class
# generated files
bin/
gen/
# Local configuration file (sdk path, etc)
local.properties
/local.properties
# Eclipse
.classpath
.project
.settings
# Android Studio (InteliJ)
.idea/
/.idea/workspace.xml
*.iml
*.iws
*.ipr
/*/out
/*/build
/*/*/production
#Gradle
.gradletasknamecache
.gradle/
build/
bin/
#Crashlytics
com_crashlytics_export_strings.xml
#OSx
.DS_Store
================================================
FILE: CHANGELOG.md
================================================
# Changelog
# 2.3.0 (11/05/2017)
- Fix Toolbar TextView's layout race condition. [@ansman](https://github.com/ansman) #386, #368, #327, #280, #304, #363
# 2.2.0 (05/04/2016)
- Added AppCompat Styles (AppCompatTextView will now pickup textViewStyle etc). Thanks @paul-turner
- Fix for Toolbar not inflating `TextView`s upfront.
# 2.1.0 (27/04/2015)
- Fixed #155, We now clone correctly.
- Added Styles for Custom Views. (`builder.addCustomStyle(ToggleButton.class, android.R.attr.buttonStyleToggle)`)
# 2.0.2 (05/01/2015)
- Fixed `CalligraphyConfig.Builder` missing return statements.
- Fixed `createView()` getting the wrong parent context, Fixed: #135, #120
# 2.0.1 (28/01/2014)
- Throw exception on passing null into `CalligraphySpan`
- Fixed memory bug with `Toolbar`. [@dlew](https://github.com/dlew)
# 2.0.0 (16/01/2014)
**Breaking changes**
This is a massive rewrite of the interception model. Look at `CalligraphyLayoutInflater` and
`CalligraphyConfig` for more information on options and changes.
- **BREAKING CHANGE** This is an API change to Calligraphy config.
Changed CalligraphyConfig to a builder pattern, use `CalligraphyConfig.Builder().build()`;
Notable changes:
- Removed jar binary, We build an @aar due to the way we tag `View`s.
- Intercept View creation at each stage.
- Defer view creation to native components (Except CustomViews).
- Inject `setPrivateFactory` on the `Activity`.
- We wrap Factory not disturbing underlying factory and layout inflater invocation.
- Better support for `cloneInContext()` which the compat library uses heavily.
# 1.2.0 (20/10/2014)
- Fixes issues with `appcompat-v7:21+` (uses underlying `Toolbar` impl).
- Lollipop support.
- Fast path view with font already set by us.
# 1.1.0 (02/08/2014)
- Fixes ActionBar Title/SubTitle `textStyles`.
- Fixes `textAllCaps` bug, now works correctly.
- Fixes some `Spannable` issues reported, we are more careful what we apply `Spannable`'s too now.
- Fixes missing Typeface on hint text on `EditText`/`AutoComplete`.
- Fixes empty source and javadoc jars on maven.
# 1.0.0 (05/07/2014)
- Added ActionBar Title/SubTitle support.
- Toast support via default style/or TextView theme style.
- Removed FontFamily parsing as it lead to users not being able to use `fontFamily`
- Added TextAppearance Support - Thanks [@codebutler](https://github.com/codebutler) & [@loganj](https://github.com/loganj)
- Default Font no longer required.
# 0.8/9 (Skipped major API change)
# 0.7.1 (22/04/2014)
- Fixed Resources not found Exception - [@Smuldr](https://github.com/Smuldr)
# 0.7.0 (28/01/2014)
- Added Anti-aliasing support
- Added custom font attribute support - Thanks [@Roman Zhilich](https://github.com/RomanZhilich)
- Changed Maven groupId to `uk.co.chrisjenx` artifact is now `calligraphy`. `compile 'uk.co.chrisjenx:calligraphy:0.+'`
# 0.6.0 (02/01/2014)
- Supports all Android implementations of `TextView`
- Supports Custom `TextView`s - Thanks [@mironov-nsk](https://github.com/mironov-nsk)
- Caches none found fonts as null
# 0.5.0
- Added support for `Button` class
# 0.4.0
- Initial Release
================================================
FILE: CalligraphySample/.gitignore
================================================
/build
================================================
FILE: CalligraphySample/build.gradle
================================================
apply plugin: 'com.android.application'
android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
defaultConfig {
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode project.ext.versionCodeInt
versionName version
}
buildTypes {
debug {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
}
dependencies {
implementation project(':calligraphy')
implementation "com.android.support:support-v4:${supportLibraryVersion}"
implementation "com.android.support:appcompat-v7:${supportLibraryVersion}"
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
// debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.3.1'
debugImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
}
================================================
FILE: CalligraphySample/proguard-rules.txt
================================================
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /Developer/android-sdk-osx/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the ProGuard
# include property in project.properties.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
-keep class butterknife.** { *; }
-dontwarn butterknife.internal.**
-keep class **$$ViewBinder { *; }
-keepclasseswithmembernames class * {
@butterknife.* <fields>;
}
-keepclasseswithmembernames class * {
@butterknife.* <methods>;
}
================================================
FILE: CalligraphySample/src/main/AndroidManifest.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<manifest
package="uk.co.chrisjenx.calligraphy.sample"
xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:name=".CalligraphyApplication"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name="uk.co.chrisjenx.calligraphy.sample.MainActivity"
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>
================================================
FILE: CalligraphySample/src/main/java/uk/co/chrisjenx/calligraphy/sample/CalligraphyApplication.java
================================================
package uk.co.chrisjenx.calligraphy.sample;
import android.app.Application;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
/**
* Created by chris on 06/05/2014.
* For Calligraphy.
*/
public class CalligraphyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/Roboto-ThinItalic.ttf")
.setFontAttrId(R.attr.fontPath)
.addCustomViewWithSetTypeface(CustomViewWithTypefaceSupport.class)
.addCustomStyle(TextField.class, R.attr.textFieldStyle)
.build()
);
}
}
================================================
FILE: CalligraphySample/src/main/java/uk/co/chrisjenx/calligraphy/sample/CustomTextView.java
================================================
package uk.co.chrisjenx.calligraphy.sample;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
public class CustomTextView extends TextView {
public CustomTextView(Context context) {
super(context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
}
================================================
FILE: CalligraphySample/src/main/java/uk/co/chrisjenx/calligraphy/sample/CustomViewWithTypefaceSupport.java
================================================
package uk.co.chrisjenx.calligraphy.sample;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
/**
* @author Dmitriy Tarasov
*/
public class CustomViewWithTypefaceSupport extends View {
private Paint paint;
private Rect textBounds;
private int width;
private int height;
public CustomViewWithTypefaceSupport(Context context) {
super(context);
init();
}
public CustomViewWithTypefaceSupport(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomViewWithTypefaceSupport(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public CustomViewWithTypefaceSupport(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init() {
paint = new Paint();
paint.setTextSize(50);
textBounds = new Rect();
}
@Override
protected void onDraw(Canvas canvas) {
String text = "This is a custom view with setTypeface support";
Paint.FontMetrics fm = paint.getFontMetrics();
paint.getTextBounds(text, 0, text.length(), textBounds);
width = textBounds.left + textBounds.right + getPaddingLeft() + getPaddingRight();
height = (int) (Math.abs(fm.top) + fm.bottom);
canvas.drawText(text, 0, -fm.top + getPaddingTop(), paint);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(width, height);
}
/**
* Used by Calligraphy to change view's typeface
*/
@SuppressWarnings("unused")
public void setTypeface(Typeface tf) {
paint.setTypeface(tf);
invalidate();
}
}
================================================
FILE: CalligraphySample/src/main/java/uk/co/chrisjenx/calligraphy/sample/MainActivity.java
================================================
package uk.co.chrisjenx.calligraphy.sample;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
import static butterknife.ButterKnife.findById;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Toolbar toolbar = findById(this, R.id.toolbar);
setSupportActionBar(toolbar);
// Inject pragmatically
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, PlaceholderFragment.getInstance())
.commit();
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
// toolbar.setTitle("Calligraphy Added");
toolbar.setSubtitle("Added subtitle");
}
}, 1000);
handler.postDelayed(new Runnable() {
@Override public void run() {
toolbar.setTitle(null);
toolbar.setSubtitle("Added subtitle");
}
}, 2000);
handler.postDelayed(new Runnable() {
@Override public void run() {
toolbar.setTitle("Calligraphy added back");
toolbar.setSubtitle("Added subtitle");
}
}, 3000);
}
/*
Uncomment if you disable PrivateFactory injection. See CalligraphyConfig#disablePrivateFactoryInjection()
*/
// @Override
// @TargetApi(Build.VERSION_CODES.HONEYCOMB)
// public View onCreateView(View parent, String name, @NonNull Context context, @NonNull AttributeSet attrs) {
// return CalligraphyContextWrapper.onActivityCreateView(this, parent, super.onCreateView(parent, name, context, attrs), name, context, attrs);
// }
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
}
================================================
FILE: CalligraphySample/src/main/java/uk/co/chrisjenx/calligraphy/sample/PlaceholderFragment.java
================================================
package uk.co.chrisjenx.calligraphy.sample;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* A placeholder fragment containing a simple view.
*/
public class PlaceholderFragment extends Fragment {
public static Fragment getInstance() {
return new PlaceholderFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this, view);
}
@OnClick(R.id.button_bold)
public void onClickBoldButton() {
Toast.makeText(getActivity(), "Custom Typeface toast text", Toast.LENGTH_SHORT).show();
}
@OnClick(R.id.button_default)
public void onClickDefaultButton() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Custom Typeface Dialog");
builder.setTitle("Sample Dialog");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
}
================================================
FILE: CalligraphySample/src/main/java/uk/co/chrisjenx/calligraphy/sample/TextField.java
================================================
package uk.co.chrisjenx.calligraphy.sample;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* Created by chris on 17/03/15.
* For Calligraphy.
*/
public class TextField extends TextView {
public TextField(final Context context, final AttributeSet attrs) {
super(context, attrs, R.attr.textFieldStyle);
}
}
================================================
FILE: CalligraphySample/src/main/res/layout/activity_main.xml
================================================
<merge
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="uk.co.chrisjenx.calligraphy.sample.MainActivity"
tools:ignore="MergeRootFrame">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/primary_material_light"
android:minHeight="?attr/actionBarSize"
android:translationZ="4dp"
android:theme="@style/ThemeOverlay.AppCompat.Light"/>
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"
/>
</merge>
================================================
FILE: CalligraphySample/src/main/res/layout/fragment_main.xml
================================================
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="uk.co.chrisjenx.calligraphy.sample.PlaceholderFragment"
tools:ignore="MissingPrefix">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/default_theme"/>
<TextView
fontPath="fonts/Roboto-Bold.ttf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/defined_fontpath_view"/>
<TextView
fontPath="fonts/Roboto-None.ttf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/defined_incorrect"/>
<TextView
style="@style/AppTheme.Widget.TextView.Style"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/defined_in_style"/>
<TextView
style="@style/AppTheme.Widget.TextViewAppearanceStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/defined_in_appears_style"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/defined_in_appears"
android:textAppearance="@style/TextAppearance.FontPathView"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:singleLine="true"
android:text="@string/defined_in_appears"
android:textAppearance="@style/TextAppearance.FontPathView"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/defined_in_appears_caps"
android:textAllCaps="true"
android:textAppearance="@style/TextAppearance.FontPathView"/>
<uk.co.chrisjenx.calligraphy.sample.CustomTextView
fontPath="fonts/Oswald-Stencbab.ttf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/defined_custom_view"/>
<uk.co.chrisjenx.calligraphy.sample.CustomViewWithTypefaceSupport
fontPath="fonts/Oswald-Stencbab.ttf"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ViewStub
android:id="@+id/stub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout="@layout/stub"/>
<ViewStub
android:id="@+id/stub_with_font_path"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout="@layout/stub_with_font_path"/>
<CheckBox
fontPath="fonts/Oswald-Stencbab.ttf"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:text="@string/checkbox_custom"/>
<EditText
android:id="@+id/edit_text"
fontPath="fonts/Roboto-Bold.ttf"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:hint="@string/edit_text_hint"/>
<uk.co.chrisjenx.calligraphy.sample.TextField
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/custom_view_style_text"/>
<Button
android:id="@+id/button_default"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:text="@string/button_default"/>
<Button
android:id="@+id/button_bold"
fontPath="fonts/Roboto-Bold.ttf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="12dp"
android:text="@string/button_defined"/>
</LinearLayout>
</ScrollView>
================================================
FILE: CalligraphySample/src/main/res/layout/stub.xml
================================================
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/defined_view_stub"/>
================================================
FILE: CalligraphySample/src/main/res/layout/stub_with_font_path.xml
================================================
<TextView
fontPath="fonts/Oswald-Stencbab.ttf"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/defined_view_stub_font_path"
tools:ignore="MissingPrefix"/>
================================================
FILE: CalligraphySample/src/main/res/values/attrs.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="textFieldStyle" format="reference"/>
</resources>
================================================
FILE: CalligraphySample/src/main/res/values/dimens.xml
================================================
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
</resources>
================================================
FILE: CalligraphySample/src/main/res/values/strings.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Calligraphy</string>
<string name="defined_gtw">\nThis is text set by the gtw style.\n</string>
<string name="default_theme">\nThis is text set by the default theme fontPath.\n</string>
<string name="defined_fontpath_view">\nThis has a font path set to Roboto Bold, on the View.\n</string>
<string name="defined_incorrect">\nThis has a fontPath set to a font file that does not exist, it goes back to the default.\n</string>
<string name="defined_in_style">\nThis has the font path defined in the style as Roboto Condensed.\n</string>
<string name="defined_in_appears_style">\nThis has the font path defined in the Styles TextAppearance as Roboto Condensed.\n</string>
<string name="defined_in_appears">\nThis has the font path defined in the Views TextAppearance as Oswald.\n</string>
<string name="defined_in_appears_caps">\nThis has the font path defined in the Views TextAppearance as Oswald. textAllCaps is applied.\n</string>
<string name="defined_custom_view">\nThis is a custom TextView with Oswald font.\n</string>
<string name="defined_view_stub">\nThis is a TextView inflated from a ViewStub.\n</string>
<string name="defined_view_stub_font_path">\nThis is a TextView inflated from a ViewStub w/ fontPath declared.\n</string>
<string name="checkbox_custom">Custom Oswald checkbox</string>
<string name="edit_text_hint">Custom Roboto Bold Hint</string>
<string name="custom_view_style_text">\nCustom View Style, taken from a Custom style attribute.\n</string>
<string name="button_default">Default Font (show dialog)</string>
<string name="button_defined">Bold Button (show toast)</string>
</resources>
================================================
FILE: CalligraphySample/src/main/res/values/styles.xml
================================================
<resources
xmlns:tools="http://schemas.android.com/tools"
tools:ignore="NewApi">
<!-- Base application theme. -->
<!--<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">-->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="android:textViewStyle">@style/AppTheme.Widget.TextView</item>
<!-- Action Bar Theme -->
<item name="android:actionBarStyle">@style/AppTheme.ActionBar</item>
<!-- Custom Style Attribute-->
<item name="textFieldStyle">@style/TextField</item>
</style>
<!-- AppTheme ActionBar Style -->
<style name="AppTheme.ActionBar" parent="android:Widget.Holo.Light.ActionBar.Solid.Inverse">
<item name="android:titleTextStyle">@style/AppTheme.ActionBar.TextAppearance</item>
<item name="android:subtitleTextStyle">@style/AppTheme.ActionBar.TextAppearance.SubTitle</item>
</style>
<style name="AppTheme.ActionBar.TextAppearance" parent="TextAppearance.AppCompat.Widget.ActionBar.Title.Inverse">
<item name="fontPath">fonts/Oswald-Stencbab.ttf</item>
</style>
<style name="AppTheme.ActionBar.TextAppearance.SubTitle" parent="TextAppearance.AppCompat.Widget.ActionBar.Subtitle.Inverse">
<item name="fontPath">fonts/gtw.ttf</item>
</style>
<style name="AppTheme.Widget"/>
<style name="TextViewNoStyleParent">
<item name="android:textColor">@android:color/holo_blue_dark</item>
<item name="fontPath">fonts/gtw.ttf</item>
</style>
<style name="AppTheme.Widget.TextView" parent="android:Widget.Holo.Light.TextView">
<!-- Custom Attr-->
<item name="fontPath">fonts/RobotoCondensed-Regular.ttf</item>
</style>
<style name="AppTheme.Widget.TextView.Style">
<item name="fontPath">fonts/RobotoCondensed-Regular.ttf</item>
</style>
<style name="AppTheme.Widget.TextViewAppearanceStyle" parent="android:Widget.Holo.Light.TextView">
<item name="android:textAppearance">@style/TextAppearance.FontPath</item>
</style>
<style name="TextAppearance.FontPath" parent="android:TextAppearance">
<!-- Custom Attr-->
<item name="fontPath">fonts/RobotoCondensed-Regular.ttf</item>
<item name="android:textColor">#444</item>
</style>
<style name="TextAppearance.FontPathView" parent="android:TextAppearance">
<!-- Custom Attr-->
<item name="fontPath">fonts/Oswald-Stencbab.ttf</item>
<item name="android:textColor">#444</item>
</style>
<!-- Custom Class Styles -->
<style name="TextField" parent="android:Widget.Holo.Light.TextView">
<item name="fontPath">fonts/gtw.ttf</item>
<item name="android:textSize">@dimen/abc_text_size_small_material</item>
</style>
</resources>
================================================
FILE: CalligraphySample/src/main/res/values-w820dp/dimens.xml
================================================
<resources>
<!-- Example customization of dimensions originally defined in res/values/dimens.xml
(such as screen margins) for screens with more than 820dp of available width. This
would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->
<dimen name="activity_horizontal_margin">64dp</dimen>
</resources>
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2013 Christopher Jenkins
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
# This version of Calligraphy has reached its end-of-life and is no longer maintained. Please migrate to [Calligraphy 3](https://github.com/InflationX/Calligraphy)!
Calligraphy
===========
[](http://android-arsenal.com/details/1/163)
Custom fonts in Android an OK way.
Are you fed up of Custom Views to set fonts? Or traversing the ViewTree to find TextViews? Yeah me too.

## Getting started
### Dependency
Include the dependency [Download (.aar)](http://search.maven.org/remotecontent?filepath=uk/co/chrisjenx/calligraphy/2.3.0/calligraphy-2.3.0.aar) :
```groovy
dependencies {
compile 'uk.co.chrisjenx:calligraphy:2.3.0'
}
```
### Add Fonts
Add your custom fonts to `assets/`. All font definitions are relative to this path.
Assuming that you are using Gradle you should create the assets directory under `src/main/` in your project directory if it does not already exist.
As it's popular to use multi-project build with Gradle the path is usually `app/src/main/assets/`, where `app` is the project name.
You might consider creating a `fonts/` subdirectory in the assets directory (as in examples).
### Usage
```xml
<TextView fontPath="fonts/MyFont.ttf"/>
```
**Note: The missing namespace, this __IS__ intentional.**
### Installation
Define your default font using `CalligraphyConfig`, in your `Application` class in the `#onCreate()` method.
```java
@Override
public void onCreate() {
super.onCreate();
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/Roboto-RobotoRegular.ttf")
.setFontAttrId(R.attr.fontPath)
.build()
);
//....
}
```
_Note: You don't need to define `CalligraphyConfig` but the library will apply
no default font and use the default attribute of `R.attr.fontPath`._
### Inject into Context
Wrap the `Activity` Context:
```java
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
```
_You're good to go!_
## Usage
### Custom font per TextView
```xml
<TextView
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
fontPath="fonts/Roboto-Bold.ttf"/>
```
_Note: Popular IDE's (Android Studio, IntelliJ) will likely mark this as an error despite being correct. You may want to add `tools:ignore="MissingPrefix"` to either the View itself or its parent ViewGroup to avoid this. You'll need to add the tools namespace to have access to this "ignore" attribute. `xmlns:tools="
http://schemas.android.com/tools"`. See https://code.google.com/p/android/issues/detail?id=65176._
### Custom font in TextAppearance
```xml
<style name="TextAppearance.FontPath" parent="android:TextAppearance">
<!-- Custom Attr-->
<item name="fontPath">fonts/RobotoCondensed-Regular.ttf</item>
</style>
```
```xml
<TextView
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="@style/TextAppearance.FontPath"/>
```
### Custom font in Styles
```xml
<style name="TextViewCustomFont">
<item name="fontPath">fonts/RobotoCondensed-Regular.ttf</item>
</style>
```
### Custom font defined in Theme
```xml
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<item name="android:textViewStyle">@style/AppTheme.Widget.TextView</item>
</style>
<style name="AppTheme.Widget"/>
<style name="AppTheme.Widget.TextView" parent="android:Widget.Holo.Light.TextView">
<item name="fontPath">fonts/Roboto-ThinItalic.ttf</item>
</style>
```
# FAQ
### Font Resolution
The `CalligraphyFactory` looks for the font in a pretty specific order, for the _most part_ it's
very similar to how the Android framework resolves attributes.
1. `View` xml - attr defined here will always take priority.
2. `Style` xml - attr defined here is checked next.
3. `TextAppearance` xml - attr is checked next, the only caveat to this is **IF** you have a font
defined in the `Style` and a `TextAttribute` defined in the `View` the `Style` attribute is picked first!
4. `Theme` - if defined this is used.
5. `Default` - if defined in the `CalligraphyConfig` this is used of none of the above are found
**OR** if one of the above returns an invalid font.
### Why *not* piggyback off of fontFamily attribute?
We originally did, but it conflicted with users wanting to actually use that attribute, you now
have to define a custom attribute.
### Why no jar?
We needed to ship a custom ID with Calligraphy to improve the Font Injection flow. This
unfortunately means that it has to be an `aar`. But you're using Gradle now anyway right?
### Multiple Typeface's per TextView / Spannables
It is possible to use multiple Typefaces inside a `TextView`, this isn't new concept to Android.
This _could_ be achieved using something like the following code.
```java
SpannableStringBuilder sBuilder = new SpannableStringBuilder();
sBuilder.append("Hello!") // Bold this
.append("I use Calligraphy"); // Default TextView font.
// Create the Typeface you want to apply to certain text
CalligraphyTypefaceSpan typefaceSpan = new CalligraphyTypefaceSpan(TypefaceUtils.load(getAssets(), "fonts/Roboto-Bold.ttf"));
// Apply typeface to the Spannable 0 - 6 "Hello!" This can of course by dynamic.
sBuilder.setSpan(typefaceSpan, 0, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
setText(sBuilder, TextView.BufferType.SPANNABLE);
```
Of course this is just an example. Your mileage may vary.
### Exceptions / Pitfalls
To our knowledge (try: `grep -r -e "void set[^(]*(Typeface " <android source dir>`) there are two standard Android widgets that have multiple methods to set typefaces. They are:
- android.support.v7.widget.SwitchCompat
- android.widget.Switch
Both have a method called `setSwitchTypeface` that sets the typeface within the switch (e.g. on/off, yes/no). `SetTypeface` sets the typeface of the label. You will need to create your own subclass that overrides `setTypeface` and calls both `super.setTypeface` and `super.setSwitchTypeface`.
# Collaborators
- [@mironov-nsk](https://github.com/mironov-nsk)
- [@Roman Zhilich](https://github.com/RomanZhilich)
- [@Smuldr](https://github.com/Smuldr)
- [@Codebutler](https://github.com/codebutler)
- [@loganj](https://github.com/loganj)
- [@dlew](https://github.com/dlew)
- [@ansman](https://github.com/ansman)
# Note
This library was created because it is currently not possible to declare a custom font in XML files in Android.
If you feel this should be possible to do, please star [this issue](https://code.google.com/p/android/issues/detail?id=88945) on the official Android bug tracker.
# Licence
Copyright 2013 Christopher Jenkins
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
[](http://www.libtastic.com/technology/79/)
================================================
FILE: build.gradle
================================================
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.1'
}
}
allprojects {
repositories {
jcenter()
google()
}
// Is Release Build?
version = getProperty('VERSION_NAME')
ext {
isReleaseVersion = has("release")
versionCodeInt = getProperty('VERSION_CODE').toInteger()
supportLibraryVersion = '27.1.1'
buildToolsVersion = '27.0.3'
compileSdkVersion = 27
minSdkVersion = 14
targetSdkVersion = 27
}
}
task wrapper(type: Wrapper) {
gradleVersion = '3.5'
distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-bin.zip"
}
================================================
FILE: calligraphy/.gitignore
================================================
/build
================================================
FILE: calligraphy/build.gradle
================================================
apply plugin: 'com.android.library'
apply from: rootProject.file('gradle/deploy.gradle')
android {
compileSdkVersion project.compileSdkVersion
buildToolsVersion project.buildToolsVersion
defaultConfig {
minSdkVersion project.minSdkVersion
targetSdkVersion project.targetSdkVersion
versionCode project.versionCodeInt
versionName version
consumerProguardFiles 'consumer-proguard-rules.txt'
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'consumer-proguard-rules.txt'
}
}
}
dependencies {
api "com.android.support:appcompat-v7:${supportLibraryVersion}"
}
================================================
FILE: calligraphy/consumer-proguard-rules.txt
================================================
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /Developer/android-sdk-osx/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the ProGuard
# include property in project.properties.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
-keep class uk.co.chrisjenx.calligraphy.* { *; }
-keep class uk.co.chrisjenx.calligraphy.*$* { *; }
================================================
FILE: calligraphy/gradle.properties
================================================
# SubProject Library Gradle Properties
# See parent properties for global properties
POM_NAME=Calligraphy
POM_ARTIFACT_ID=calligraphy
POM_PACKAGING=aar
================================================
FILE: calligraphy/src/main/AndroidManifest.xml
================================================
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="uk.co.chrisjenx.calligraphy">
<application />
</manifest>
================================================
FILE: calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyActivityFactory.java
================================================
package uk.co.chrisjenx.calligraphy;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
/**
* Created by chris on 09/11/14.
* For Calligraphy.
*/
interface CalligraphyActivityFactory {
/**
* Used to Wrap the Activity onCreateView method.
*
* You implement this method like so in your base activity.
* <pre>
* {@code
* public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
* return CalligraphyContextWrapper.get(getBaseContext()).onActivityCreateView(super.onCreateView(parent, name, context, attrs), attrs);
* }
* }
* </pre>
*
* @param parent parent view, can be null.
* @param view result of {@code super.onCreateView(parent, name, context, attrs)}, this might be null, which is fine.
* @param name Name of View we are trying to inflate
* @param context current context (normally the Activity's)
* @param attrs see {@link android.view.LayoutInflater.Factory2#onCreateView(android.view.View, String, android.content.Context, android.util.AttributeSet)} @return the result from the activities {@code onCreateView()}
* @return The view passed in, or null if nothing was passed in.
* @see android.view.LayoutInflater.Factory2
*/
View onActivityCreateView(View parent, View view, String name, Context context, AttributeSet attrs);
}
================================================
FILE: calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyConfig.java
================================================
package uk.co.chrisjenx.calligraphy;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.MultiAutoCompleteTextView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.ToggleButton;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Created by chris on 20/12/2013
* Project: Calligraphy
*/
public class CalligraphyConfig {
/**
* The default styles for the factory to lookup. The builder builds an extended immutable
* map of this with any additional custom styles.
*/
private static final Map<Class<? extends TextView>, Integer> DEFAULT_STYLES = new HashMap<>();
static {
{
DEFAULT_STYLES.put(TextView.class, android.R.attr.textViewStyle);
DEFAULT_STYLES.put(Button.class, android.R.attr.buttonStyle);
DEFAULT_STYLES.put(EditText.class, android.R.attr.editTextStyle);
DEFAULT_STYLES.put(AutoCompleteTextView.class, android.R.attr.autoCompleteTextViewStyle);
DEFAULT_STYLES.put(MultiAutoCompleteTextView.class, android.R.attr.autoCompleteTextViewStyle);
DEFAULT_STYLES.put(CheckBox.class, android.R.attr.checkboxStyle);
DEFAULT_STYLES.put(RadioButton.class, android.R.attr.radioButtonStyle);
DEFAULT_STYLES.put(ToggleButton.class, android.R.attr.buttonStyleToggle);
if (CalligraphyUtils.canAddV7AppCompatViews()) {
addAppCompatViews();
}
}
}
/**
* AppCompat will inflate special versions of views for Material tinting etc,
* this adds those classes to the style lookup map
*/
private static void addAppCompatViews() {
DEFAULT_STYLES.put(android.support.v7.widget.AppCompatTextView.class, android.R.attr.textViewStyle);
DEFAULT_STYLES.put(android.support.v7.widget.AppCompatButton.class, android.R.attr.buttonStyle);
DEFAULT_STYLES.put(android.support.v7.widget.AppCompatEditText.class, android.R.attr.editTextStyle);
DEFAULT_STYLES.put(android.support.v7.widget.AppCompatAutoCompleteTextView.class, android.R.attr.autoCompleteTextViewStyle);
DEFAULT_STYLES.put(android.support.v7.widget.AppCompatMultiAutoCompleteTextView.class, android.R.attr.autoCompleteTextViewStyle);
DEFAULT_STYLES.put(android.support.v7.widget.AppCompatCheckBox.class, android.R.attr.checkboxStyle);
DEFAULT_STYLES.put(android.support.v7.widget.AppCompatRadioButton.class, android.R.attr.radioButtonStyle);
DEFAULT_STYLES.put(android.support.v7.widget.AppCompatCheckedTextView.class, android.R.attr.checkedTextViewStyle);
}
private static CalligraphyConfig sInstance;
/**
* Set the default Calligraphy Config
*
* @param calligraphyConfig the config build using the builder.
* @see uk.co.chrisjenx.calligraphy.CalligraphyConfig.Builder
*/
public static void initDefault(CalligraphyConfig calligraphyConfig) {
sInstance = calligraphyConfig;
}
/**
* The current Calligraphy Config.
* If not set it will create a default config.
*/
public static CalligraphyConfig get() {
if (sInstance == null)
sInstance = new CalligraphyConfig(new Builder());
return sInstance;
}
/**
* Is a default font set?
*/
private final boolean mIsFontSet;
/**
* The default Font Path if nothing else is setup.
*/
private final String mFontPath;
/**
* Default Font Path Attr Id to lookup
*/
private final int mAttrId;
/**
* Use Reflection to inject the private factory.
*/
private final boolean mReflection;
/**
* Use Reflection to intercept CustomView inflation with the correct Context.
*/
private final boolean mCustomViewCreation;
/**
* Use Reflection to try to set typeface for custom views if they has setTypeface method
*/
private final boolean mCustomViewTypefaceSupport;
/**
* Class Styles. Build from DEFAULT_STYLES and the builder.
*/
private final Map<Class<? extends TextView>, Integer> mClassStyleAttributeMap;
/**
* Collection of custom non-{@code TextView}'s registered for applying typeface during inflation
* @see uk.co.chrisjenx.calligraphy.CalligraphyConfig.Builder#addCustomViewWithSetTypeface(Class)
*/
private final Set<Class<?>> hasTypefaceViews;
protected CalligraphyConfig(Builder builder) {
mIsFontSet = builder.isFontSet;
mFontPath = builder.fontAssetPath;
mAttrId = builder.attrId;
mReflection = builder.reflection;
mCustomViewCreation = builder.customViewCreation;
mCustomViewTypefaceSupport = builder.customViewTypefaceSupport;
final Map<Class<? extends TextView>, Integer> tempMap = new HashMap<>(DEFAULT_STYLES);
tempMap.putAll(builder.mStyleClassMap);
mClassStyleAttributeMap = Collections.unmodifiableMap(tempMap);
hasTypefaceViews = Collections.unmodifiableSet(builder.mHasTypefaceClasses);
}
/**
* @return mFontPath for text views might be null
*/
public String getFontPath() {
return mFontPath;
}
/**
* @return true if set, false if null|empty
*/
boolean isFontSet() {
return mIsFontSet;
}
public boolean isReflection() {
return mReflection;
}
public boolean isCustomViewCreation() {
return mCustomViewCreation;
}
public boolean isCustomViewTypefaceSupport() {
return mCustomViewTypefaceSupport;
}
public boolean isCustomViewHasTypeface(View view) {
return hasTypefaceViews.contains(view.getClass());
}
/* default */ Map<Class<? extends TextView>, Integer> getClassStyles() {
return mClassStyleAttributeMap;
}
/**
* @return the custom attrId to look for, -1 if not set.
*/
public int getAttrId() {
return mAttrId;
}
public static class Builder {
/**
* Default AttrID if not set.
*/
public static final int INVALID_ATTR_ID = -1;
/**
* Use Reflection to inject the private factory. Doesn't exist pre HC. so defaults to false.
*/
private boolean reflection = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
/**
* Use Reflection to intercept CustomView inflation with the correct Context.
*/
private boolean customViewCreation = true;
/**
* Use Reflection during view creation to try change typeface via setTypeface method if it exists
*/
private boolean customViewTypefaceSupport = false;
/**
* The fontAttrId to look up the font path from.
*/
private int attrId = R.attr.fontPath;
/**
* Has the user set the default font path.
*/
private boolean isFontSet = false;
/**
* The default fontPath
*/
private String fontAssetPath = null;
/**
* Additional Class Styles. Can be empty.
*/
private Map<Class<? extends TextView>, Integer> mStyleClassMap = new HashMap<>();
private Set<Class<?>> mHasTypefaceClasses = new HashSet<>();
/**
* This defaults to R.attr.fontPath. So only override if you want to use your own attrId.
*
* @param fontAssetAttrId the custom attribute to look for fonts in assets.
* @return this builder.
*/
public Builder setFontAttrId(int fontAssetAttrId) {
this.attrId = fontAssetAttrId;
return this;
}
/**
* Set the default font if you don't define one else where in your styles.
*
* @param defaultFontAssetPath a path to a font file in the assets folder, e.g. "fonts/Roboto-light.ttf",
* passing null will default to the device font-family.
* @return this builder.
*/
public Builder setDefaultFontPath(String defaultFontAssetPath) {
this.isFontSet = !TextUtils.isEmpty(defaultFontAssetPath);
this.fontAssetPath = defaultFontAssetPath;
return this;
}
/**
* <p>Turn of the use of Reflection to inject the private factory.
* This has operational consequences! Please read and understand before disabling.
* <b>This is already disabled on pre Honeycomb devices. (API 11)</b></p>
*
* <p> If you disable this you will need to override your {@link android.app.Activity#onCreateView(android.view.View, String, android.content.Context, android.util.AttributeSet)}
* as this is set as the {@link android.view.LayoutInflater} private factory.</p>
* <br>
* <b> Use the following code in the Activity if you disable FactoryInjection:</b>
* <pre><code>
* {@literal @}Override
* {@literal @}TargetApi(Build.VERSION_CODES.HONEYCOMB)
* public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
* return CalligraphyContextWrapper.onActivityCreateView(this, parent, super.onCreateView(parent, name, context, attrs), name, context, attrs);
* }
* </code></pre>
*/
public Builder disablePrivateFactoryInjection() {
this.reflection = false;
return this;
}
/**
* Due to the poor inflation order where custom views are created and never returned inside an
* {@code onCreateView(...)} method. We have to create CustomView's at the latest point in the
* overrideable injection flow.
*
* On HoneyComb+ this is inside the {@link android.app.Activity#onCreateView(android.view.View, String, android.content.Context, android.util.AttributeSet)}
* Pre HoneyComb this is in the {@link android.view.LayoutInflater.Factory#onCreateView(String, android.util.AttributeSet)}
*
* We wrap base implementations, so if you LayoutInflater/Factory/Activity creates the
* custom view before we get to this point, your view is used. (Such is the case with the
* TintEditText etc)
*
* The problem is, the native methods pass there parents context to the constructor in a really
* specific place. We have to mimic this in {@link uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater#createCustomViewInternal(android.view.View, android.view.View, String, android.content.Context, android.util.AttributeSet)}
* To mimic this we have to use reflection as the Class constructor args are hidden to us.
*
* We have discussed other means of doing this but this is the only semi-clean way of doing it.
* (Without having to do proxy classes etc).
*
* Calling this will of course speed up inflation by turning off reflection, but not by much,
* But if you want Calligraphy to inject the correct typeface then you will need to make sure your CustomView's
* are created before reaching the LayoutInflater onViewCreated.
*/
public Builder disableCustomViewInflation() {
this.customViewCreation = false;
return this;
}
/**
* Add a custom style to get looked up. If you use a custom class that has a parent style
* which is not part of the default android styles you will need to add it here.
*
* The Calligraphy inflater is unaware of custom styles in your custom classes. We use
* the class type to look up the style attribute in the theme resources.
*
* So if you had a {@code MyTextField.class} which looked up it's default style as
* {@code R.attr.textFieldStyle} you would add those here.
*
* {@code builder.addCustomStyle(MyTextField.class,R.attr.textFieldStyle}
*
* @param styleClass the class that related to the parent styleResource. null is ignored.
* @param styleResourceAttribute e.g. {@code R.attr.textFieldStyle}, 0 is ignored.
* @return this builder.
*/
public Builder addCustomStyle(final Class<? extends TextView> styleClass, final int styleResourceAttribute) {
if (styleClass == null || styleResourceAttribute == 0) return this;
mStyleClassMap.put(styleClass, styleResourceAttribute);
return this;
}
/**
* Register custom non-{@code TextView}'s which implement {@code setTypeface} so they can have the Typeface applied during inflation.
*/
public Builder addCustomViewWithSetTypeface(Class<?> clazz) {
customViewTypefaceSupport = true;
mHasTypefaceClasses.add(clazz);
return this;
}
public CalligraphyConfig build() {
this.isFontSet = !TextUtils.isEmpty(fontAssetPath);
return new CalligraphyConfig(this);
}
}
}
================================================
FILE: calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyContextWrapper.java
================================================
package uk.co.chrisjenx.calligraphy;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
/**
* Created by chris on 19/12/2013
* Project: Calligraphy
*/
public class CalligraphyContextWrapper extends ContextWrapper {
private CalligraphyLayoutInflater mInflater;
private final int mAttributeId;
/**
* Uses the default configuration from {@link uk.co.chrisjenx.calligraphy.CalligraphyConfig}
*
* Remember if you are defining default in the
* {@link uk.co.chrisjenx.calligraphy.CalligraphyConfig} make sure this is initialised before
* the activity is created.
*
* @param base ContextBase to Wrap.
* @return ContextWrapper to pass back to the activity.
*/
public static ContextWrapper wrap(Context base) {
return new CalligraphyContextWrapper(base);
}
/**
* You only need to call this <b>IF</b> you call
* {@link uk.co.chrisjenx.calligraphy.CalligraphyConfig.Builder#disablePrivateFactoryInjection()}
* This will need to be called from the
* {@link android.app.Activity#onCreateView(android.view.View, String, android.content.Context, android.util.AttributeSet)}
* method to enable view font injection if the view is created inside the activity onCreateView.
*
* You would implement this method like so in you base activity.
* <pre>
* {@code
* public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
* return CalligraphyContextWrapper.onActivityCreateView(this, parent, super.onCreateView(parent, name, context, attrs), name, context, attrs);
* }
* }
* </pre>
*
* @param activity The activity the original that the ContextWrapper was attached too.
* @param parent Parent view from onCreateView
* @param view The View Created inside onCreateView or from super.onCreateView
* @param name The View name from onCreateView
* @param context The context from onCreateView
* @param attr The AttributeSet from onCreateView
* @return The same view passed in, or null if null passed in.
*/
public static View onActivityCreateView(Activity activity, View parent, View view, String name, Context context, AttributeSet attr) {
return get(activity).onActivityCreateView(parent, view, name, context, attr);
}
/**
* Get the Calligraphy Activity Fragment Instance to allow callbacks for when views are created.
*
* @param activity The activity the original that the ContextWrapper was attached too.
* @return Interface allowing you to call onActivityViewCreated
*/
static CalligraphyActivityFactory get(Activity activity) {
if (!(activity.getLayoutInflater() instanceof CalligraphyLayoutInflater)) {
throw new RuntimeException("This activity does not wrap the Base Context! See CalligraphyContextWrapper.wrap(Context)");
}
return (CalligraphyActivityFactory) activity.getLayoutInflater();
}
/**
* Uses the default configuration from {@link uk.co.chrisjenx.calligraphy.CalligraphyConfig}
*
* Remember if you are defining default in the
* {@link uk.co.chrisjenx.calligraphy.CalligraphyConfig} make sure this is initialised before
* the activity is created.
*
* @param base ContextBase to Wrap
*/
CalligraphyContextWrapper(Context base) {
super(base);
mAttributeId = CalligraphyConfig.get().getAttrId();
}
/**
* Override the default AttributeId, this will always take the custom attribute defined here
* and ignore the one set in {@link uk.co.chrisjenx.calligraphy.CalligraphyConfig}.
*
* Remember if you are defining default in the
* {@link uk.co.chrisjenx.calligraphy.CalligraphyConfig} make sure this is initialised before
* the activity is created.
*
* @param base ContextBase to Wrap
* @param attributeId Attribute to lookup.
* @deprecated use {@link #wrap(android.content.Context)}
*/
@Deprecated
public CalligraphyContextWrapper(Context base, int attributeId) {
super(base);
mAttributeId = attributeId;
}
@Override
public Object getSystemService(String name) {
if (LAYOUT_INFLATER_SERVICE.equals(name)) {
if (mInflater == null) {
mInflater = new CalligraphyLayoutInflater(LayoutInflater.from(getBaseContext()), this, mAttributeId, false);
}
return mInflater;
}
return super.getSystemService(name);
}
}
================================================
FILE: calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyFactory.java
================================================
package uk.co.chrisjenx.calligraphy;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Typeface;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
import java.lang.reflect.Method;
class CalligraphyFactory {
private static final String ACTION_BAR_TITLE = "action_bar_title";
private static final String ACTION_BAR_SUBTITLE = "action_bar_subtitle";
/**
* Some styles are in sub styles, such as actionBarTextStyle etc..
*
* @param view view to check.
* @return 2 element array, default to -1 unless a style has been found.
*/
protected static int[] getStyleForTextView(TextView view) {
final int[] styleIds = new int[]{-1, -1};
// Try to find the specific actionbar styles
if (isActionBarTitle(view)) {
styleIds[0] = android.R.attr.actionBarStyle;
styleIds[1] = android.R.attr.titleTextStyle;
} else if (isActionBarSubTitle(view)) {
styleIds[0] = android.R.attr.actionBarStyle;
styleIds[1] = android.R.attr.subtitleTextStyle;
}
if (styleIds[0] == -1) {
// Use TextAppearance as default style
styleIds[0] = CalligraphyConfig.get().getClassStyles().containsKey(view.getClass())
? CalligraphyConfig.get().getClassStyles().get(view.getClass())
: android.R.attr.textAppearance;
}
return styleIds;
}
/**
* An even dirtier way to see if the TextView is part of the ActionBar
*
* @param view TextView to check is Title
* @return true if it is.
*/
@SuppressLint("NewApi")
protected static boolean isActionBarTitle(TextView view) {
if (matchesResourceIdName(view, ACTION_BAR_TITLE)) return true;
if (parentIsToolbarV7(view)) {
final android.support.v7.widget.Toolbar parent = (android.support.v7.widget.Toolbar) view.getParent();
return TextUtils.equals(parent.getTitle(), view.getText());
}
return false;
}
/**
* An even dirtier way to see if the TextView is part of the ActionBar
*
* @param view TextView to check is Title
* @return true if it is.
*/
@SuppressLint("NewApi")
protected static boolean isActionBarSubTitle(TextView view) {
if (matchesResourceIdName(view, ACTION_BAR_SUBTITLE)) return true;
if (parentIsToolbarV7(view)) {
final android.support.v7.widget.Toolbar parent = (android.support.v7.widget.Toolbar) view.getParent();
return TextUtils.equals(parent.getSubtitle(), view.getText());
}
return false;
}
protected static boolean parentIsToolbarV7(View view) {
return CalligraphyUtils.canCheckForV7Toolbar() && view.getParent() != null && (view.getParent() instanceof android.support.v7.widget.Toolbar);
}
/**
* Use to match a view against a potential view id. Such as ActionBar title etc.
*
* @param view not null view you want to see has resource matching name.
* @param matches not null resource name to match against. Its not case sensitive.
* @return true if matches false otherwise.
*/
protected static boolean matchesResourceIdName(View view, String matches) {
if (view.getId() == View.NO_ID) return false;
final String resourceEntryName = view.getResources().getResourceEntryName(view.getId());
return resourceEntryName.equalsIgnoreCase(matches);
}
private final int[] mAttributeId;
public CalligraphyFactory(int attributeId) {
this.mAttributeId = new int[]{attributeId};
}
/**
* Handle the created view
*
* @param view nullable.
* @param context shouldn't be null.
* @param attrs shouldn't be null.
* @return null if null is passed in.
*/
public View onViewCreated(View view, Context context, AttributeSet attrs) {
if (view != null && view.getTag(R.id.calligraphy_tag_id) != Boolean.TRUE) {
onViewCreatedInternal(view, context, attrs);
view.setTag(R.id.calligraphy_tag_id, Boolean.TRUE);
}
return view;
}
void onViewCreatedInternal(View view, final Context context, AttributeSet attrs) {
if (view instanceof TextView) {
// Fast path the setting of TextView's font, means if we do some delayed setting of font,
// which has already been set by use we skip this TextView (mainly for inflating custom,
// TextView's inside the Toolbar/ActionBar).
if (TypefaceUtils.isLoaded(((TextView) view).getTypeface())) {
return;
}
// Try to get typeface attribute value
// Since we're not using namespace it's a little bit tricky
// Check xml attrs, style attrs and text appearance for font path
String textViewFont = resolveFontPath(context, attrs);
// Try theme attributes
if (TextUtils.isEmpty(textViewFont)) {
final int[] styleForTextView = getStyleForTextView((TextView) view);
if (styleForTextView[1] != -1)
textViewFont = CalligraphyUtils.pullFontPathFromTheme(context, styleForTextView[0], styleForTextView[1], mAttributeId);
else
textViewFont = CalligraphyUtils.pullFontPathFromTheme(context, styleForTextView[0], mAttributeId);
}
// Still need to defer the Native action bar, appcompat-v7:21+ uses the Toolbar underneath. But won't match these anyway.
final boolean deferred = matchesResourceIdName(view, ACTION_BAR_TITLE) || matchesResourceIdName(view, ACTION_BAR_SUBTITLE);
CalligraphyUtils.applyFontToTextView(context, (TextView) view, CalligraphyConfig.get(), textViewFont, deferred);
}
// AppCompat API21+ The ActionBar doesn't inflate default Title/SubTitle, we need to scan the
// Toolbar(Which underlies the ActionBar) for its children.
if (CalligraphyUtils.canCheckForV7Toolbar() && view instanceof android.support.v7.widget.Toolbar) {
applyFontToToolbar((Toolbar) view);
}
// Try to set typeface for custom views using interface method or via reflection if available
if (view instanceof HasTypeface) {
Typeface typeface = getDefaultTypeface(context, resolveFontPath(context, attrs));
if (typeface != null) {
((HasTypeface) view).setTypeface(typeface);
}
} else if (CalligraphyConfig.get().isCustomViewTypefaceSupport() && CalligraphyConfig.get().isCustomViewHasTypeface(view)) {
final Method setTypeface = ReflectionUtils.getMethod(view.getClass(), "setTypeface");
String fontPath = resolveFontPath(context, attrs);
Typeface typeface = getDefaultTypeface(context, fontPath);
if (setTypeface != null && typeface != null) {
ReflectionUtils.invokeMethod(view, setTypeface, typeface);
}
}
}
private Typeface getDefaultTypeface(Context context, String fontPath) {
if (TextUtils.isEmpty(fontPath)) {
fontPath = CalligraphyConfig.get().getFontPath();
}
if (!TextUtils.isEmpty(fontPath)) {
return TypefaceUtils.load(context.getAssets(), fontPath);
}
return null;
}
/**
* Resolving font path from xml attrs, style attrs or text appearance
*/
private String resolveFontPath(Context context, AttributeSet attrs) {
// Try view xml attributes
String textViewFont = CalligraphyUtils.pullFontPathFromView(context, attrs, mAttributeId);
// Try view style attributes
if (TextUtils.isEmpty(textViewFont)) {
textViewFont = CalligraphyUtils.pullFontPathFromStyle(context, attrs, mAttributeId);
}
// Try View TextAppearance
if (TextUtils.isEmpty(textViewFont)) {
textViewFont = CalligraphyUtils.pullFontPathFromTextAppearance(context, attrs, mAttributeId);
}
return textViewFont;
}
/**
* Will forcibly set text on the views then remove ones that didn't have copy.
*
* @param view toolbar view.
*/
private void applyFontToToolbar(final Toolbar view) {
final CharSequence previousTitle = view.getTitle();
final CharSequence previousSubtitle = view.getSubtitle();
// The toolbar inflates both the title and the subtitle views lazily but luckily they do it
// synchronously when you set a title and a subtitle programmatically.
// So we set a title and a subtitle to something, then get the views, then revert.
view.setTitle("uk.co.chrisjenx.calligraphy:toolbar_title");
view.setSubtitle("uk.co.chrisjenx.calligraphy:toolbar_subtitle");
// Iterate through the children to run post inflation on them
final int childCount = view.getChildCount();
for (int i = 0; i < childCount; i++) {
onViewCreated(view.getChildAt(i), view.getContext(), null);
}
// Remove views from view if they didn't have copy set.
view.setTitle(previousTitle);
view.setSubtitle(previousSubtitle);
}
}
================================================
FILE: calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyLayoutInflater.java
================================================
package uk.co.chrisjenx.calligraphy;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import org.xmlpull.v1.XmlPullParser;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* Created by chris on 19/12/2013
* Project: Calligraphy
*/
class CalligraphyLayoutInflater extends LayoutInflater implements CalligraphyActivityFactory {
private static final String[] sClassPrefixList = {
"android.widget.",
"android.webkit."
};
private final int mAttributeId;
private final CalligraphyFactory mCalligraphyFactory;
// Reflection Hax
private boolean mSetPrivateFactory = false;
private Field mConstructorArgs = null;
protected CalligraphyLayoutInflater(Context context, int attributeId) {
super(context);
mAttributeId = attributeId;
mCalligraphyFactory = new CalligraphyFactory(attributeId);
setUpLayoutFactories(false);
}
protected CalligraphyLayoutInflater(LayoutInflater original, Context newContext, int attributeId, final boolean cloned) {
super(original, newContext);
mAttributeId = attributeId;
mCalligraphyFactory = new CalligraphyFactory(attributeId);
setUpLayoutFactories(cloned);
}
@Override
public LayoutInflater cloneInContext(Context newContext) {
return new CalligraphyLayoutInflater(this, newContext, mAttributeId, true);
}
// ===
// Wrapping goodies
// ===
@Override
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
setPrivateFactoryInternal();
return super.inflate(parser, root, attachToRoot);
}
/**
* We don't want to unnecessary create/set our factories if there are none there. We try to be
* as lazy as possible.
*/
private void setUpLayoutFactories(boolean cloned) {
if (cloned) return;
// If we are HC+ we get and set Factory2 otherwise we just wrap Factory1
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (getFactory2() != null && !(getFactory2() instanceof WrapperFactory2)) {
// Sets both Factory/Factory2
setFactory2(getFactory2());
}
}
// We can do this as setFactory2 is used for both methods.
if (getFactory() != null && !(getFactory() instanceof WrapperFactory)) {
setFactory(getFactory());
}
}
@Override
public void setFactory(Factory factory) {
// Only set our factory and wrap calls to the Factory trying to be set!
if (!(factory instanceof WrapperFactory)) {
super.setFactory(new WrapperFactory(factory, this, mCalligraphyFactory));
} else {
super.setFactory(factory);
}
}
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void setFactory2(Factory2 factory2) {
// Only set our factory and wrap calls to the Factory2 trying to be set!
if (!(factory2 instanceof WrapperFactory2)) {
// LayoutInflaterCompat.setFactory(this, new WrapperFactory2(factory2, mCalligraphyFactory));
super.setFactory2(new WrapperFactory2(factory2, mCalligraphyFactory));
} else {
super.setFactory2(factory2);
}
}
private void setPrivateFactoryInternal() {
// Already tried to set the factory.
if (mSetPrivateFactory) return;
// Reflection (Or Old Device) skip.
if (!CalligraphyConfig.get().isReflection()) return;
// Skip if not attached to an activity.
if (!(getContext() instanceof Factory2)) {
mSetPrivateFactory = true;
return;
}
final Method setPrivateFactoryMethod = ReflectionUtils
.getMethod(LayoutInflater.class, "setPrivateFactory");
if (setPrivateFactoryMethod != null) {
ReflectionUtils.invokeMethod(this,
setPrivateFactoryMethod,
new PrivateWrapperFactory2((Factory2) getContext(), this, mCalligraphyFactory));
}
mSetPrivateFactory = true;
}
// ===
// LayoutInflater ViewCreators
// Works in order of inflation
// ===
/**
* The Activity onCreateView (PrivateFactory) is the third port of call for LayoutInflation.
* We opted to manual injection over aggressive reflection, this should be less fragile.
*/
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public View onActivityCreateView(View parent, View view, String name, Context context, AttributeSet attrs) {
return mCalligraphyFactory.onViewCreated(createCustomViewInternal(parent, view, name, context, attrs), context, attrs);
}
/**
* The LayoutInflater onCreateView is the fourth port of call for LayoutInflation.
* BUT only for none CustomViews.
*/
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
protected View onCreateView(View parent, String name, AttributeSet attrs) throws ClassNotFoundException {
return mCalligraphyFactory.onViewCreated(super.onCreateView(parent, name, attrs),
getContext(), attrs);
}
/**
* The LayoutInflater onCreateView is the fourth port of call for LayoutInflation.
* BUT only for none CustomViews.
* Basically if this method doesn't inflate the View nothing probably will.
*/
@Override
protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
// This mimics the {@code PhoneLayoutInflater} in the way it tries to inflate the base
// classes, if this fails its pretty certain the app will fail at this point.
View view = null;
for (String prefix : sClassPrefixList) {
try {
view = createView(name, prefix, attrs);
} catch (ClassNotFoundException ignored) {
}
}
// In this case we want to let the base class take a crack
// at it.
if (view == null) view = super.onCreateView(name, attrs);
return mCalligraphyFactory.onViewCreated(view, view.getContext(), attrs);
}
/**
* Nasty method to inflate custom layouts that haven't been handled else where. If this fails it
* will fall back through to the PhoneLayoutInflater method of inflating custom views where
* Calligraphy will NOT have a hook into.
*
* @param parent parent view
* @param view view if it has been inflated by this point, if this is not null this method
* just returns this value.
* @param name name of the thing to inflate.
* @param viewContext Context to inflate by if parent is null
* @param attrs Attr for this view which we can steal fontPath from too.
* @return view or the View we inflate in here.
*/
private View createCustomViewInternal(View parent, View view, String name, Context viewContext, AttributeSet attrs) {
// I by no means advise anyone to do this normally, but Google have locked down access to
// the createView() method, so we never get a callback with attributes at the end of the
// createViewFromTag chain (which would solve all this unnecessary rubbish).
// We at the very least try to optimise this as much as possible.
// We only call for customViews (As they are the ones that never go through onCreateView(...)).
// We also maintain the Field reference and make it accessible which will make a pretty
// significant difference to performance on Android 4.0+.
// If CustomViewCreation is off skip this.
if (!CalligraphyConfig.get().isCustomViewCreation()) return view;
if (view == null && name.indexOf('.') > -1) {
if (mConstructorArgs == null)
mConstructorArgs = ReflectionUtils.getField(LayoutInflater.class, "mConstructorArgs");
final Object[] mConstructorArgsArr = (Object[]) ReflectionUtils.getValue(mConstructorArgs, this);
final Object lastContext = mConstructorArgsArr[0];
// The LayoutInflater actually finds out the correct context to use. We just need to set
// it on the mConstructor for the internal method.
// Set the constructor ars up for the createView, not sure why we can't pass these in.
mConstructorArgsArr[0] = viewContext;
ReflectionUtils.setValue(mConstructorArgs, this, mConstructorArgsArr);
try {
view = createView(name, null, attrs);
} catch (ClassNotFoundException ignored) {
} finally {
mConstructorArgsArr[0] = lastContext;
ReflectionUtils.setValue(mConstructorArgs, this, mConstructorArgsArr);
}
}
return view;
}
// ===
// Wrapper Factories for Pre/Post HC
// ===
/**
* Factory 1 is the first port of call for LayoutInflation
*/
private static class WrapperFactory implements Factory {
private final Factory mFactory;
private final CalligraphyLayoutInflater mInflater;
private final CalligraphyFactory mCalligraphyFactory;
public WrapperFactory(Factory factory, CalligraphyLayoutInflater inflater, CalligraphyFactory calligraphyFactory) {
mFactory = factory;
mInflater = inflater;
mCalligraphyFactory = calligraphyFactory;
}
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
return mCalligraphyFactory.onViewCreated(
mInflater.createCustomViewInternal(
null, mFactory.onCreateView(name, context, attrs), name, context, attrs
),
context, attrs
);
}
return mCalligraphyFactory.onViewCreated(
mFactory.onCreateView(name, context, attrs),
context, attrs
);
}
}
/**
* Factory 2 is the second port of call for LayoutInflation
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private static class WrapperFactory2 implements Factory2 {
protected final Factory2 mFactory2;
protected final CalligraphyFactory mCalligraphyFactory;
public WrapperFactory2(Factory2 factory2, CalligraphyFactory calligraphyFactory) {
mFactory2 = factory2;
mCalligraphyFactory = calligraphyFactory;
}
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
return mCalligraphyFactory.onViewCreated(
mFactory2.onCreateView(name, context, attrs),
context, attrs);
}
@Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
return mCalligraphyFactory.onViewCreated(
mFactory2.onCreateView(parent, name, context, attrs),
context, attrs);
}
}
/**
* Private factory is step three for Activity Inflation, this is what is attached to the
* Activity on HC+ devices.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private static class PrivateWrapperFactory2 extends WrapperFactory2 {
private final CalligraphyLayoutInflater mInflater;
public PrivateWrapperFactory2(Factory2 factory2, CalligraphyLayoutInflater inflater, CalligraphyFactory calligraphyFactory) {
super(factory2, calligraphyFactory);
mInflater = inflater;
}
@Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
return mCalligraphyFactory.onViewCreated(
mInflater.createCustomViewInternal(parent,
mFactory2.onCreateView(parent, name, context, attrs),
name, context, attrs
),
context, attrs
);
}
}
}
================================================
FILE: calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyTypefaceSpan.java
================================================
package uk.co.chrisjenx.calligraphy;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.style.MetricAffectingSpan;
public class CalligraphyTypefaceSpan extends MetricAffectingSpan {
private final Typeface typeface;
public CalligraphyTypefaceSpan(final Typeface typeface) {
if (typeface == null) {
throw new IllegalArgumentException("typeface is null");
}
this.typeface = typeface;
}
@Override
public void updateDrawState(final TextPaint drawState) {
apply(drawState);
}
@Override
public void updateMeasureState(final TextPaint paint) {
apply(paint);
}
private void apply(final Paint paint) {
final Typeface oldTypeface = paint.getTypeface();
final int oldStyle = oldTypeface != null ? oldTypeface.getStyle() : 0;
final int fakeStyle = oldStyle & ~typeface.getStyle();
if ((fakeStyle & Typeface.BOLD) != 0) {
paint.setFakeBoldText(true);
}
if ((fakeStyle & Typeface.ITALIC) != 0) {
paint.setTextSkewX(-0.25f);
}
paint.setTypeface(typeface);
}
}
================================================
FILE: calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyUtils.java
================================================
package uk.co.chrisjenx.calligraphy;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;
/**
* Created by chris on 20/12/2013
* Project: Calligraphy
*/
public final class CalligraphyUtils {
public static final int[] ANDROID_ATTR_TEXT_APPEARANCE = new int[]{android.R.attr.textAppearance};
/**
* Applies a custom typeface span to the text.
*
* @param s text to apply it too.
* @param typeface typeface to apply.
* @return Either the passed in Object or new Spannable with the typeface span applied.
*/
public static CharSequence applyTypefaceSpan(CharSequence s, Typeface typeface) {
if (s != null && s.length() > 0) {
if (!(s instanceof Spannable)) {
s = new SpannableString(s);
}
((Spannable) s).setSpan(TypefaceUtils.getSpan(typeface), 0, s.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return s;
}
/**
* Applies a Typeface to a TextView.
* Defaults to false for deferring, if you are having issues with the textview keeping
* the custom Typeface, use
* {@link #applyFontToTextView(android.widget.TextView, android.graphics.Typeface, boolean)}
*
* @param textView Not null, TextView or child of.
* @param typeface Not null, Typeface to apply to the TextView.
* @return true if applied otherwise false.
* @see #applyFontToTextView(android.widget.TextView, android.graphics.Typeface, boolean)
*/
public static boolean applyFontToTextView(final TextView textView, final Typeface typeface) {
return applyFontToTextView(textView, typeface, false);
}
/**
* Applies a Typeface to a TextView, if deferred,its recommend you don't call this multiple
* times, as this adds a TextWatcher.
*
* Deferring should really only be used on tricky views which get Typeface set by the system at
* weird times.
*
* @param textView Not null, TextView or child of.
* @param typeface Not null, Typeface to apply to the TextView.
* @param deferred If true we use Typefaces and TextChange listener to make sure font is always
* applied, but this sometimes conflicts with other
* {@link android.text.Spannable}'s.
* @return true if applied otherwise false.
* @see #applyFontToTextView(android.widget.TextView, android.graphics.Typeface)
*/
public static boolean applyFontToTextView(final TextView textView, final Typeface typeface, boolean deferred) {
if (textView == null || typeface == null) return false;
textView.setPaintFlags(textView.getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
textView.setTypeface(typeface);
if (deferred) {
textView.setText(applyTypefaceSpan(textView.getText(), typeface), TextView.BufferType.SPANNABLE);
textView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
applyTypefaceSpan(s, typeface);
}
});
}
return true;
}
/**
* Useful for manually fonts to a TextView. Will not default back to font
* set in {@link uk.co.chrisjenx.calligraphy.CalligraphyConfig}
*
* @param context Context
* @param textView Not null, TextView to apply to.
* @param filePath if null/empty will do nothing.
* @return true if fonts been applied
*/
public static boolean applyFontToTextView(final Context context, final TextView textView, final String filePath) {
return applyFontToTextView(context, textView, filePath, false);
}
static boolean applyFontToTextView(final Context context, final TextView textView, final String filePath, boolean deferred) {
if (textView == null || context == null) return false;
final AssetManager assetManager = context.getAssets();
final Typeface typeface = TypefaceUtils.load(assetManager, filePath);
return applyFontToTextView(textView, typeface, deferred);
}
static void applyFontToTextView(final Context context, final TextView textView, final CalligraphyConfig config) {
applyFontToTextView(context, textView, config, false);
}
static void applyFontToTextView(final Context context, final TextView textView, final CalligraphyConfig config, boolean deferred) {
if (context == null || textView == null || config == null) return;
if (!config.isFontSet()) return;
applyFontToTextView(context, textView, config.getFontPath(), deferred);
}
/**
* Applies font to TextView. Will fall back to the default one if not set.
*
* @param context context
* @param textView textView to apply to.
* @param config Default Config
* @param textViewFont nullable, will use Default Config if null or fails to find the
* defined font.
*/
public static void applyFontToTextView(final Context context, final TextView textView, final CalligraphyConfig config, final String textViewFont) {
applyFontToTextView(context, textView, config, textViewFont, false);
}
static void applyFontToTextView(final Context context, final TextView textView, final CalligraphyConfig config, final String textViewFont, boolean deferred) {
if (context == null || textView == null || config == null) return;
if (!TextUtils.isEmpty(textViewFont) && applyFontToTextView(context, textView, textViewFont, deferred)) {
return;
}
applyFontToTextView(context, textView, config, deferred);
}
/**
* Tries to pull the Custom Attribute directly from the TextView.
*
* @param context Activity Context
* @param attrs View Attributes
* @param attributeId if -1 returns null.
* @return null if attribute is not defined or added to View
*/
static String pullFontPathFromView(Context context, AttributeSet attrs, int[] attributeId) {
if (attributeId == null || attrs == null)
return null;
final String attributeName;
try {
attributeName = context.getResources().getResourceEntryName(attributeId[0]);
} catch (Resources.NotFoundException e) {
// invalid attribute ID
return null;
}
final int stringResourceId = attrs.getAttributeResourceValue(null, attributeName, -1);
return stringResourceId > 0
? context.getString(stringResourceId)
: attrs.getAttributeValue(null, attributeName);
}
/**
* Tries to pull the Font Path from the View Style as this is the next decendent after being
* defined in the View's xml.
*
* @param context Activity Activity Context
* @param attrs View Attributes
* @param attributeId if -1 returns null.
* @return null if attribute is not defined or found in the Style
*/
static String pullFontPathFromStyle(Context context, AttributeSet attrs, int[] attributeId) {
if (attributeId == null || attrs == null)
return null;
final TypedArray typedArray = context.obtainStyledAttributes(attrs, attributeId);
if (typedArray != null) {
try {
// First defined attribute
String fontFromAttribute = typedArray.getString(0);
if (!TextUtils.isEmpty(fontFromAttribute)) {
return fontFromAttribute;
}
} catch (Exception ignore) {
// Failed for some reason.
} finally {
typedArray.recycle();
}
}
return null;
}
/**
* Tries to pull the Font Path from the Text Appearance.
*
* @param context Activity Context
* @param attrs View Attributes
* @param attributeId if -1 returns null.
* @return returns null if attribute is not defined or if no TextAppearance is found.
*/
static String pullFontPathFromTextAppearance(final Context context, AttributeSet attrs, int[] attributeId) {
if (attributeId == null || attrs == null) {
return null;
}
int textAppearanceId = -1;
final TypedArray typedArrayAttr = context.obtainStyledAttributes(attrs, ANDROID_ATTR_TEXT_APPEARANCE);
if (typedArrayAttr != null) {
try {
textAppearanceId = typedArrayAttr.getResourceId(0, -1);
} catch (Exception ignored) {
// Failed for some reason
return null;
} finally {
typedArrayAttr.recycle();
}
}
final TypedArray textAppearanceAttrs = context.obtainStyledAttributes(textAppearanceId, attributeId);
if (textAppearanceAttrs != null) {
try {
return textAppearanceAttrs.getString(0);
} catch (Exception ignore) {
// Failed for some reason.
return null;
} finally {
textAppearanceAttrs.recycle();
}
}
return null;
}
/**
* Last but not least, try to pull the Font Path from the Theme, which is defined.
*
* @param context Activity Context
* @param styleAttrId Theme style id
* @param attributeId if -1 returns null.
* @return null if no theme or attribute defined.
*/
static String pullFontPathFromTheme(Context context, int styleAttrId, int[] attributeId) {
if (styleAttrId == -1 || attributeId == null)
return null;
final Resources.Theme theme = context.getTheme();
final TypedValue value = new TypedValue();
theme.resolveAttribute(styleAttrId, value, true);
final TypedArray typedArray = theme.obtainStyledAttributes(value.resourceId, attributeId);
try {
String font = typedArray.getString(0);
return font;
} catch (Exception ignore) {
// Failed for some reason.
return null;
} finally {
typedArray.recycle();
}
}
/**
* Last but not least, try to pull the Font Path from the Theme, which is defined.
*
* @param context Activity Context
* @param styleAttrId Theme style id
* @param subStyleAttrId the sub style from the theme to look up after the first style
* @param attributeId if -1 returns null.
* @return null if no theme or attribute defined.
*/
static String pullFontPathFromTheme(Context context, int styleAttrId, int subStyleAttrId, int[] attributeId) {
if (styleAttrId == -1 || attributeId == null)
return null;
final Resources.Theme theme = context.getTheme();
final TypedValue value = new TypedValue();
theme.resolveAttribute(styleAttrId, value, true);
int subStyleResId = -1;
final TypedArray parentTypedArray = theme.obtainStyledAttributes(value.resourceId, new int[]{subStyleAttrId});
try {
subStyleResId = parentTypedArray.getResourceId(0, -1);
} catch (Exception ignore) {
// Failed for some reason.
return null;
} finally {
parentTypedArray.recycle();
}
if (subStyleResId == -1) return null;
final TypedArray subTypedArray = context.obtainStyledAttributes(subStyleResId, attributeId);
if (subTypedArray != null) {
try {
return subTypedArray.getString(0);
} catch (Exception ignore) {
// Failed for some reason.
return null;
} finally {
subTypedArray.recycle();
}
}
return null;
}
private static Boolean sToolbarCheck = null;
private static Boolean sAppCompatViewCheck = null;
/**
* See if the user has added appcompat-v7, this is done at runtime, so we only check once.
*
* @return true if the v7.Toolbar is on the classpath
*/
static boolean canCheckForV7Toolbar() {
if (sToolbarCheck == null) {
try {
Class.forName("android.support.v7.widget.Toolbar");
sToolbarCheck = Boolean.TRUE;
} catch (ClassNotFoundException e) {
sToolbarCheck = Boolean.FALSE;
}
}
return sToolbarCheck;
}
/**
* See if the user has added appcompat-v7 with AppCompatViews
*
* @return true if AppcompatTextView is on the classpath
*/
static boolean canAddV7AppCompatViews() {
if (sAppCompatViewCheck == null) {
try {
Class.forName("android.support.v7.widget.AppCompatTextView");
sAppCompatViewCheck = Boolean.TRUE;
} catch (ClassNotFoundException e) {
sAppCompatViewCheck = Boolean.FALSE;
}
}
return sAppCompatViewCheck;
}
private CalligraphyUtils() {
}
}
================================================
FILE: calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/HasTypeface.java
================================================
package uk.co.chrisjenx.calligraphy;
import android.graphics.Typeface;
/**
* There are two ways to set typeface for custom views:
* <ul>
* <li>Implementing this interface. You should only implements {@link #setTypeface(Typeface)} method.</li>
* <li>Or via reflection. If custom view already has setTypeface method you can
* register it during Calligraphy configuration
* {@link uk.co.chrisjenx.calligraphy.CalligraphyConfig.Builder#addCustomViewWithSetTypeface(Class)}</li>
* </ul>
* First way is faster but encourage more effort from the developer to implements interface. Second one
* requires less effort but works slowly cause reflection calls.
*
* @author Dmitriy Tarasov
*/
public interface HasTypeface {
void setTypeface(Typeface typeface);
}
================================================
FILE: calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/ReflectionUtils.java
================================================
package uk.co.chrisjenx.calligraphy;
import android.util.Log;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Created by chris on 17/12/14.
* For Calligraphy.
*/
class ReflectionUtils {
private static final String TAG = ReflectionUtils.class.getSimpleName();
static Field getField(Class clazz, String fieldName) {
try {
final Field f = clazz.getDeclaredField(fieldName);
f.setAccessible(true);
return f;
} catch (NoSuchFieldException ignored) {
}
return null;
}
static Object getValue(Field field, Object obj) {
try {
return field.get(obj);
} catch (IllegalAccessException ignored) {
}
return null;
}
static void setValue(Field field, Object obj, Object value) {
try {
field.set(obj, value);
} catch (IllegalAccessException ignored) {
}
}
static Method getMethod(Class clazz, String methodName) {
final Method[] methods = clazz.getMethods();
for (Method method : methods) {
if (method.getName().equals(methodName)) {
method.setAccessible(true);
return method;
}
}
return null;
}
static void invokeMethod(Object object, Method method, Object... args) {
try {
if (method == null) return;
method.invoke(object, args);
} catch (IllegalAccessException | InvocationTargetException e) {
Log.d(TAG, "Can't invoke method using reflection", e);
}
}
}
================================================
FILE: calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/TypefaceUtils.java
================================================
package uk.co.chrisjenx.calligraphy;
import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.util.Log;
import java.util.HashMap;
import java.util.Map;
/**
* A helper loading {@link android.graphics.Typeface} avoiding the leak of the font when loaded
* by multiple calls to {@link android.graphics.Typeface#createFromAsset(android.content.res.AssetManager, String)}
* on pre-ICS versions.
* <p>
* More details can be found here https://code.google.com/p/android/issues/detail?id=9904
* <p>
* Created by Chris Jenkins on 04/09/13.
*/
public final class TypefaceUtils {
private static final Map<String, Typeface> sCachedFonts = new HashMap<String, Typeface>();
private static final Map<Typeface, CalligraphyTypefaceSpan> sCachedSpans = new HashMap<Typeface, CalligraphyTypefaceSpan>();
/**
* A helper loading a custom font.
*
* @param assetManager App's asset manager.
* @param filePath The path of the file.
* @return Return {@link android.graphics.Typeface} or null if the path is invalid.
*/
public static Typeface load(final AssetManager assetManager, final String filePath) {
synchronized (sCachedFonts) {
try {
if (!sCachedFonts.containsKey(filePath)) {
final Typeface typeface = Typeface.createFromAsset(assetManager, filePath);
sCachedFonts.put(filePath, typeface);
return typeface;
}
} catch (Exception e) {
Log.w("Calligraphy", "Can't create asset from " + filePath + ". Make sure you have passed in the correct path and file name.", e);
sCachedFonts.put(filePath, null);
return null;
}
return sCachedFonts.get(filePath);
}
}
/**
* A helper loading custom spans so we don't have to keep creating hundreds of spans.
*
* @param typeface not null typeface
* @return will return null of typeface passed in is null.
*/
public static CalligraphyTypefaceSpan getSpan(final Typeface typeface) {
if (typeface == null) return null;
synchronized (sCachedSpans) {
if (!sCachedSpans.containsKey(typeface)) {
final CalligraphyTypefaceSpan span = new CalligraphyTypefaceSpan(typeface);
sCachedSpans.put(typeface, span);
return span;
}
return sCachedSpans.get(typeface);
}
}
/**
* Is the passed in typeface one of ours?
*
* @param typeface nullable, the typeface to check if ours.
* @return true if we have loaded it false otherwise.
*/
public static boolean isLoaded(Typeface typeface) {
return typeface != null && sCachedFonts.containsValue(typeface);
}
private TypefaceUtils() {
}
}
================================================
FILE: calligraphy/src/main/res/values/attrs.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="fontPath" format="string"/>
</resources>
================================================
FILE: calligraphy/src/main/res/values/ids.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="calligraphy_tag_id" type="id"/>
</resources>
================================================
FILE: calligraphy/src/main/res/values/public.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<resources>
<public name="fontPath" type="attr"/>
</resources>
================================================
FILE: gradle/deploy.gradle
================================================
/*
* Copyright 2013 Chris Banes
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
apply plugin: 'maven'
apply plugin: 'signing'
def isReleaseBuild() {
project.ext.isReleaseVersion
}
def getReleaseRepositoryUrl() {
return "https://oss.sonatype.org/service/local/staging/deploy/maven2/"
}
def getSnapshotRepositoryUrl() {
return "https://oss.sonatype.org/content/repositories/snapshots/"
}
def getRepositoryUsername() {
return hasProperty('sonatypeUsername') ? sonatypeUsername : ""
}
def getRepositoryPassword() {
return hasProperty('sonatypePassword') ? sonatypePassword : ""
}
// Debug Build or Release?
if (isReleaseBuild()) {
println "RELEASE BUILD $version"
} else {
version += "-SNAPSHOT"
println "DEBUG BUILD $version"
}
afterEvaluate { project ->
uploadArchives {
repositories {
mavenDeployer {
beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
pom.groupId = GROUP
pom.version = version
pom.artifactId = POM_ARTIFACT_ID
repository(url: getReleaseRepositoryUrl()) {
authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())
}
snapshotRepository(url: getSnapshotRepositoryUrl()) {
authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())
}
pom.project {
name POM_NAME
packaging POM_PACKAGING
description POM_DESCRIPTION
url POM_URL
scm {
url POM_SCM_URL
connection POM_SCM_CONNECTION
developerConnection POM_SCM_DEV_CONNECTION
}
licenses {
license {
name POM_LICENCE_NAME
url POM_LICENCE_URL
distribution POM_LICENCE_DIST
}
}
developers {
developer {
id POM_DEVELOPER_ID
name POM_DEVELOPER_NAME
email POM_DEVELOPER_EMAIL
}
}
}
}
}
}
signing {
required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") }
sign configurations.archives
}
task androidJavadocs(type: Javadoc) {
source = android.sourceSets.main.java.source
classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
}
task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) {
classifier = 'javadoc'
from androidJavadocs.destinationDir
}
task androidSourcesJar(type: Jar) {
classifier = 'sources'
// from android.sourceSets.main.java
from android.sourceSets.main.java.source
}
artifacts {
archives androidSourcesJar
archives androidJavadocsJar
}
}
================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#Mon Apr 16 11:48:42 CEST 2018
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
================================================
FILE: gradle.properties
================================================
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Settings specified in this file will override any Gradle settings
# configured through the IDE.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
GROUP=uk.co.chrisjenx
VERSION_NAME=2.3.0
VERSION_CODE=24
POM_PACKAGING=aar
POM_URL=https://github.com/chrisjenx/Calligraphy
POM_DESCRIPTION=Custom Font injection through styles and attributes.
POM_SCM_URL=https://github.com/chrisjenx/Calligraphy
POM_SCM_CONNECTION=scm:git@github.com:chrisjenx/Calligraphy.git
POM_SCM_DEV_CONNECTION=scm:git@github.com:chrisjenx/Calligraphy.git
POM_LICENCE_NAME=The Apache Software License, Version 2.0
POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt
POM_LICENCE_DIST=repo
POM_DEVELOPER_ID=chrisjenx
POM_DEVELOPER_NAME=Christopher Jenkins
POM_DEVELOPER_EMAIL=chris.mark.jenkins@gmail.com
================================================
FILE: gradlew
================================================
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save ( ) {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
================================================
FILE: gradlew.bat
================================================
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
================================================
FILE: settings.gradle
================================================
include ':calligraphy', ':CalligraphySample'
gitextract_ddbcg5tt/ ├── .gitignore ├── CHANGELOG.md ├── CalligraphySample/ │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.txt │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ └── uk/ │ │ └── co/ │ │ └── chrisjenx/ │ │ └── calligraphy/ │ │ └── sample/ │ │ ├── CalligraphyApplication.java │ │ ├── CustomTextView.java │ │ ├── CustomViewWithTypefaceSupport.java │ │ ├── MainActivity.java │ │ ├── PlaceholderFragment.java │ │ └── TextField.java │ └── res/ │ ├── layout/ │ │ ├── activity_main.xml │ │ ├── fragment_main.xml │ │ ├── stub.xml │ │ └── stub_with_font_path.xml │ ├── values/ │ │ ├── attrs.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── values-w820dp/ │ └── dimens.xml ├── LICENSE ├── README.md ├── build.gradle ├── calligraphy/ │ ├── .gitignore │ ├── build.gradle │ ├── consumer-proguard-rules.txt │ ├── gradle.properties │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ └── uk/ │ │ └── co/ │ │ └── chrisjenx/ │ │ └── calligraphy/ │ │ ├── CalligraphyActivityFactory.java │ │ ├── CalligraphyConfig.java │ │ ├── CalligraphyContextWrapper.java │ │ ├── CalligraphyFactory.java │ │ ├── CalligraphyLayoutInflater.java │ │ ├── CalligraphyTypefaceSpan.java │ │ ├── CalligraphyUtils.java │ │ ├── HasTypeface.java │ │ ├── ReflectionUtils.java │ │ └── TypefaceUtils.java │ └── res/ │ └── values/ │ ├── attrs.xml │ ├── ids.xml │ └── public.xml ├── gradle/ │ ├── deploy.gradle │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat └── settings.gradle
SYMBOL INDEX (127 symbols across 16 files)
FILE: CalligraphySample/src/main/java/uk/co/chrisjenx/calligraphy/sample/CalligraphyApplication.java
class CalligraphyApplication (line 11) | public class CalligraphyApplication extends Application {
method onCreate (line 13) | @Override
FILE: CalligraphySample/src/main/java/uk/co/chrisjenx/calligraphy/sample/CustomTextView.java
class CustomTextView (line 7) | public class CustomTextView extends TextView {
method CustomTextView (line 9) | public CustomTextView(Context context) {
method CustomTextView (line 13) | public CustomTextView(Context context, AttributeSet attrs) {
method CustomTextView (line 17) | public CustomTextView(Context context, AttributeSet attrs, int defStyl...
FILE: CalligraphySample/src/main/java/uk/co/chrisjenx/calligraphy/sample/CustomViewWithTypefaceSupport.java
class CustomViewWithTypefaceSupport (line 16) | public class CustomViewWithTypefaceSupport extends View {
method CustomViewWithTypefaceSupport (line 23) | public CustomViewWithTypefaceSupport(Context context) {
method CustomViewWithTypefaceSupport (line 28) | public CustomViewWithTypefaceSupport(Context context, AttributeSet att...
method CustomViewWithTypefaceSupport (line 33) | public CustomViewWithTypefaceSupport(Context context, AttributeSet att...
method CustomViewWithTypefaceSupport (line 38) | @TargetApi(Build.VERSION_CODES.LOLLIPOP)
method init (line 44) | private void init() {
method onDraw (line 50) | @Override
method onMeasure (line 62) | @Override
method setTypeface (line 70) | @SuppressWarnings("unused")
FILE: CalligraphySample/src/main/java/uk/co/chrisjenx/calligraphy/sample/MainActivity.java
class MainActivity (line 14) | public class MainActivity extends AppCompatActivity {
method onCreate (line 16) | @Override
method attachBaseContext (line 63) | @Override
FILE: CalligraphySample/src/main/java/uk/co/chrisjenx/calligraphy/sample/PlaceholderFragment.java
class PlaceholderFragment (line 18) | public class PlaceholderFragment extends Fragment {
method getInstance (line 20) | public static Fragment getInstance() {
method onCreateView (line 24) | @Override
method onViewCreated (line 29) | @Override
method onClickBoldButton (line 35) | @OnClick(R.id.button_bold)
method onClickDefaultButton (line 40) | @OnClick(R.id.button_default)
FILE: CalligraphySample/src/main/java/uk/co/chrisjenx/calligraphy/sample/TextField.java
class TextField (line 11) | public class TextField extends TextView {
method TextField (line 13) | public TextField(final Context context, final AttributeSet attrs) {
FILE: calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyActivityFactory.java
type CalligraphyActivityFactory (line 11) | interface CalligraphyActivityFactory {
method onActivityCreateView (line 33) | View onActivityCreateView(View parent, View view, String name, Context...
FILE: calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyConfig.java
class CalligraphyConfig (line 25) | public class CalligraphyConfig {
method addAppCompatViews (line 53) | private static void addAppCompatViews() {
method initDefault (line 72) | public static void initDefault(CalligraphyConfig calligraphyConfig) {
method get (line 80) | public static CalligraphyConfig get() {
method CalligraphyConfig (line 120) | protected CalligraphyConfig(Builder builder) {
method getFontPath (line 136) | public String getFontPath() {
method isFontSet (line 143) | boolean isFontSet() {
method isReflection (line 147) | public boolean isReflection() {
method isCustomViewCreation (line 151) | public boolean isCustomViewCreation() {
method isCustomViewTypefaceSupport (line 155) | public boolean isCustomViewTypefaceSupport() {
method isCustomViewHasTypeface (line 159) | public boolean isCustomViewHasTypeface(View view) {
method getClassStyles (line 163) | Map<Class<? extends TextView>, Integer> getClassStyles() {
method getAttrId (line 170) | public int getAttrId() {
class Builder (line 174) | public static class Builder {
method setFontAttrId (line 216) | public Builder setFontAttrId(int fontAssetAttrId) {
method setDefaultFontPath (line 228) | public Builder setDefaultFontPath(String defaultFontAssetPath) {
method disablePrivateFactoryInjection (line 251) | public Builder disablePrivateFactoryInjection() {
method disableCustomViewInflation (line 279) | public Builder disableCustomViewInflation() {
method addCustomStyle (line 300) | public Builder addCustomStyle(final Class<? extends TextView> styleC...
method addCustomViewWithSetTypeface (line 309) | public Builder addCustomViewWithSetTypeface(Class<?> clazz) {
method build (line 315) | public CalligraphyConfig build() {
FILE: calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyContextWrapper.java
class CalligraphyContextWrapper (line 14) | public class CalligraphyContextWrapper extends ContextWrapper {
method wrap (line 30) | public static ContextWrapper wrap(Context base) {
method onActivityCreateView (line 58) | public static View onActivityCreateView(Activity activity, View parent...
method get (line 68) | static CalligraphyActivityFactory get(Activity activity) {
method CalligraphyContextWrapper (line 84) | CalligraphyContextWrapper(Context base) {
method CalligraphyContextWrapper (line 101) | @Deprecated
method getSystemService (line 107) | @Override
FILE: calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyFactory.java
class CalligraphyFactory (line 14) | class CalligraphyFactory {
method getStyleForTextView (line 25) | protected static int[] getStyleForTextView(TextView view) {
method isActionBarTitle (line 50) | @SuppressLint("NewApi")
method isActionBarSubTitle (line 66) | @SuppressLint("NewApi")
method parentIsToolbarV7 (line 76) | protected static boolean parentIsToolbarV7(View view) {
method matchesResourceIdName (line 87) | protected static boolean matchesResourceIdName(View view, String match...
method CalligraphyFactory (line 95) | public CalligraphyFactory(int attributeId) {
method onViewCreated (line 108) | public View onViewCreated(View view, Context context, AttributeSet att...
method onViewCreatedInternal (line 116) | void onViewCreatedInternal(View view, final Context context, Attribute...
method getDefaultTypeface (line 168) | private Typeface getDefaultTypeface(Context context, String fontPath) {
method resolveFontPath (line 181) | private String resolveFontPath(Context context, AttributeSet attrs) {
method applyFontToToolbar (line 203) | private void applyFontToToolbar(final Toolbar view) {
FILE: calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyLayoutInflater.java
class CalligraphyLayoutInflater (line 20) | class CalligraphyLayoutInflater extends LayoutInflater implements Callig...
method CalligraphyLayoutInflater (line 33) | protected CalligraphyLayoutInflater(Context context, int attributeId) {
method CalligraphyLayoutInflater (line 40) | protected CalligraphyLayoutInflater(LayoutInflater original, Context n...
method cloneInContext (line 47) | @Override
method inflate (line 57) | @Override
method setUpLayoutFactories (line 67) | private void setUpLayoutFactories(boolean cloned) {
method setFactory (line 82) | @Override
method setFactory2 (line 92) | @Override
method setPrivateFactoryInternal (line 104) | private void setPrivateFactoryInternal() {
method onActivityCreateView (line 135) | @Override
method onCreateView (line 145) | @Override
method onCreateView (line 157) | @Override
method createCustomViewInternal (line 188) | private View createCustomViewInternal(View parent, View view, String n...
class WrapperFactory (line 228) | private static class WrapperFactory implements Factory {
method WrapperFactory (line 234) | public WrapperFactory(Factory factory, CalligraphyLayoutInflater inf...
method onCreateView (line 240) | @Override
class WrapperFactory2 (line 260) | @TargetApi(Build.VERSION_CODES.HONEYCOMB)
method WrapperFactory2 (line 265) | public WrapperFactory2(Factory2 factory2, CalligraphyFactory calligr...
method onCreateView (line 270) | @Override
method onCreateView (line 277) | @Override
class PrivateWrapperFactory2 (line 289) | @TargetApi(Build.VERSION_CODES.HONEYCOMB)
method PrivateWrapperFactory2 (line 294) | public PrivateWrapperFactory2(Factory2 factory2, CalligraphyLayoutIn...
method onCreateView (line 299) | @Override
FILE: calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyTypefaceSpan.java
class CalligraphyTypefaceSpan (line 8) | public class CalligraphyTypefaceSpan extends MetricAffectingSpan {
method CalligraphyTypefaceSpan (line 11) | public CalligraphyTypefaceSpan(final Typeface typeface) {
method updateDrawState (line 19) | @Override
method updateMeasureState (line 24) | @Override
method apply (line 29) | private void apply(final Paint paint) {
FILE: calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyUtils.java
class CalligraphyUtils (line 23) | public final class CalligraphyUtils {
method applyTypefaceSpan (line 34) | public static CharSequence applyTypefaceSpan(CharSequence s, Typeface ...
method applyFontToTextView (line 55) | public static boolean applyFontToTextView(final TextView textView, fin...
method applyFontToTextView (line 74) | public static boolean applyFontToTextView(final TextView textView, fin...
method applyFontToTextView (line 107) | public static boolean applyFontToTextView(final Context context, final...
method applyFontToTextView (line 111) | static boolean applyFontToTextView(final Context context, final TextVi...
method applyFontToTextView (line 118) | static void applyFontToTextView(final Context context, final TextView ...
method applyFontToTextView (line 122) | static void applyFontToTextView(final Context context, final TextView ...
method applyFontToTextView (line 137) | public static void applyFontToTextView(final Context context, final Te...
method applyFontToTextView (line 141) | static void applyFontToTextView(final Context context, final TextView ...
method pullFontPathFromView (line 157) | static String pullFontPathFromView(Context context, AttributeSet attrs...
method pullFontPathFromStyle (line 184) | static String pullFontPathFromStyle(Context context, AttributeSet attr...
method pullFontPathFromTextAppearance (line 212) | static String pullFontPathFromTextAppearance(final Context context, At...
method pullFontPathFromTheme (line 252) | static String pullFontPathFromTheme(Context context, int styleAttrId, ...
method pullFontPathFromTheme (line 281) | static String pullFontPathFromTheme(Context context, int styleAttrId, ...
method canCheckForV7Toolbar (line 323) | static boolean canCheckForV7Toolbar() {
method canAddV7AppCompatViews (line 340) | static boolean canAddV7AppCompatViews() {
method CalligraphyUtils (line 352) | private CalligraphyUtils() {
FILE: calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/HasTypeface.java
type HasTypeface (line 18) | public interface HasTypeface {
method setTypeface (line 20) | void setTypeface(Typeface typeface);
FILE: calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/ReflectionUtils.java
class ReflectionUtils (line 13) | class ReflectionUtils {
method getField (line 17) | static Field getField(Class clazz, String fieldName) {
method getValue (line 27) | static Object getValue(Field field, Object obj) {
method setValue (line 35) | static void setValue(Field field, Object obj, Object value) {
method getMethod (line 42) | static Method getMethod(Class clazz, String methodName) {
method invokeMethod (line 53) | static void invokeMethod(Object object, Method method, Object... args) {
FILE: calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/TypefaceUtils.java
class TypefaceUtils (line 19) | public final class TypefaceUtils {
method load (line 31) | public static Typeface load(final AssetManager assetManager, final Str...
method getSpan (line 54) | public static CalligraphyTypefaceSpan getSpan(final Typeface typeface) {
method isLoaded (line 72) | public static boolean isLoaded(Typeface typeface) {
method TypefaceUtils (line 76) | private TypefaceUtils() {
Condensed preview — 49 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (131K chars).
[
{
"path": ".gitignore",
"chars": 467,
"preview": "# built application files\n*.apk\n*.ap_\n\n# files for the dex VM\n*.dex\n\n# Java class files\n*.class\n\n# generated files\nbin/\n"
},
{
"path": "CHANGELOG.md",
"chars": 3105,
"preview": "# Changelog\n\n# 2.3.0 (11/05/2017)\n- Fix Toolbar TextView's layout race condition. [@ansman](https://github.com/ansman) #"
},
{
"path": "CalligraphySample/.gitignore",
"chars": 7,
"preview": "/build\n"
},
{
"path": "CalligraphySample/build.gradle",
"chars": 1286,
"preview": "apply plugin: 'com.android.application'\n\nandroid {\n compileSdkVersion rootProject.ext.compileSdkVersion\n buildTool"
},
{
"path": "CalligraphySample/proguard-rules.txt",
"chars": 909,
"preview": "# Add project specific ProGuard rules here.\n# By default, the flags in this file are appended to flags specified\n# in /D"
},
{
"path": "CalligraphySample/src/main/AndroidManifest.xml",
"chars": 782,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest\n package=\"uk.co.chrisjenx.calligraphy.sample\"\n xmlns:android=\"htt"
},
{
"path": "CalligraphySample/src/main/java/uk/co/chrisjenx/calligraphy/sample/CalligraphyApplication.java",
"chars": 708,
"preview": "package uk.co.chrisjenx.calligraphy.sample;\n\nimport android.app.Application;\n\nimport uk.co.chrisjenx.calligraphy.Calligr"
},
{
"path": "CalligraphySample/src/main/java/uk/co/chrisjenx/calligraphy/sample/CustomTextView.java",
"chars": 500,
"preview": "package uk.co.chrisjenx.calligraphy.sample;\n\nimport android.content.Context;\nimport android.util.AttributeSet;\nimport an"
},
{
"path": "CalligraphySample/src/main/java/uk/co/chrisjenx/calligraphy/sample/CustomViewWithTypefaceSupport.java",
"chars": 2116,
"preview": "package uk.co.chrisjenx.calligraphy.sample;\n\nimport android.annotation.TargetApi;\nimport android.content.Context;\nimport"
},
{
"path": "CalligraphySample/src/main/java/uk/co/chrisjenx/calligraphy/sample/MainActivity.java",
"chars": 2277,
"preview": "package uk.co.chrisjenx.calligraphy.sample;\n\nimport android.content.Context;\nimport android.os.Bundle;\nimport android.os"
},
{
"path": "CalligraphySample/src/main/java/uk/co/chrisjenx/calligraphy/sample/PlaceholderFragment.java",
"chars": 1637,
"preview": "package uk.co.chrisjenx.calligraphy.sample;\n\nimport android.app.AlertDialog;\nimport android.content.DialogInterface;\nimp"
},
{
"path": "CalligraphySample/src/main/java/uk/co/chrisjenx/calligraphy/sample/TextField.java",
"chars": 383,
"preview": "package uk.co.chrisjenx.calligraphy.sample;\n\nimport android.content.Context;\nimport android.util.AttributeSet;\nimport an"
},
{
"path": "CalligraphySample/src/main/res/layout/activity_main.xml",
"chars": 892,
"preview": "<merge\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\""
},
{
"path": "CalligraphySample/src/main/res/layout/fragment_main.xml",
"chars": 5153,
"preview": "<ScrollView\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/t"
},
{
"path": "CalligraphySample/src/main/res/layout/stub.xml",
"chars": 202,
"preview": "<TextView\n\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"wrap_content\"\n an"
},
{
"path": "CalligraphySample/src/main/res/layout/stub_with_font_path.xml",
"chars": 336,
"preview": "<TextView\n fontPath=\"fonts/Oswald-Stencbab.ttf\"\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xm"
},
{
"path": "CalligraphySample/src/main/res/values/attrs.xml",
"chars": 118,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n\n <attr name=\"textFieldStyle\" format=\"reference\"/>\n\n</resources>"
},
{
"path": "CalligraphySample/src/main/res/values/dimens.xml",
"chars": 216,
"preview": "<resources>\n <!-- Default screen margins, per the Android Design guidelines. -->\n <dimen name=\"activity_horizontal"
},
{
"path": "CalligraphySample/src/main/res/values/strings.xml",
"chars": 1762,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n\n <string name=\"app_name\">Calligraphy</string>\n <string name=\"d"
},
{
"path": "CalligraphySample/src/main/res/values/styles.xml",
"chars": 2860,
"preview": "<resources\n xmlns:tools=\"http://schemas.android.com/tools\"\n tools:ignore=\"NewApi\">\n\n <!-- Base application them"
},
{
"path": "CalligraphySample/src/main/res/values-w820dp/dimens.xml",
"chars": 358,
"preview": "<resources>\n <!-- Example customization of dimensions originally defined in res/values/dimens.xml\n (such as s"
},
{
"path": "LICENSE",
"chars": 11317,
"preview": "Apache License\n Version 2.0, January 2004\n http://www.apache.org/licens"
},
{
"path": "README.md",
"chars": 7723,
"preview": "# This version of Calligraphy has reached its end-of-life and is no longer maintained. Please migrate to [Calligraphy 3]"
},
{
"path": "build.gradle",
"chars": 775,
"preview": "// Top-level build file where you can add configuration options common to all sub-projects/modules.\nbuildscript {\n repo"
},
{
"path": "calligraphy/.gitignore",
"chars": 7,
"preview": "/build\n"
},
{
"path": "calligraphy/build.gradle",
"chars": 724,
"preview": "apply plugin: 'com.android.library'\napply from: rootProject.file('gradle/deploy.gradle')\n\nandroid {\n compileSdkVersio"
},
{
"path": "calligraphy/consumer-proguard-rules.txt",
"chars": 767,
"preview": "# Add project specific ProGuard rules here.\n# By default, the flags in this file are appended to flags specified\n# in /D"
},
{
"path": "calligraphy/gradle.properties",
"chars": 152,
"preview": "# SubProject Library Gradle Properties\n# See parent properties for global properties\n\nPOM_NAME=Calligraphy\nPOM_ARTIFACT_"
},
{
"path": "calligraphy/src/main/AndroidManifest.xml",
"chars": 144,
"preview": "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"uk.co.chrisjenx.calligraphy\">\n <app"
},
{
"path": "calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyActivityFactory.java",
"chars": 1427,
"preview": "package uk.co.chrisjenx.calligraphy;\n\nimport android.content.Context;\nimport android.util.AttributeSet;\nimport android.v"
},
{
"path": "calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyConfig.java",
"chars": 13315,
"preview": "package uk.co.chrisjenx.calligraphy;\n\nimport android.os.Build;\nimport android.text.TextUtils;\nimport android.view.View;\n"
},
{
"path": "calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyContextWrapper.java",
"chars": 4724,
"preview": "package uk.co.chrisjenx.calligraphy;\n\nimport android.app.Activity;\nimport android.content.Context;\nimport android.conten"
},
{
"path": "calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyFactory.java",
"chars": 9431,
"preview": "package uk.co.chrisjenx.calligraphy;\n\nimport android.annotation.SuppressLint;\nimport android.content.Context;\nimport and"
},
{
"path": "calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyLayoutInflater.java",
"chars": 12406,
"preview": "package uk.co.chrisjenx.calligraphy;\n\nimport android.annotation.TargetApi;\nimport android.content.Context;\nimport androi"
},
{
"path": "calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyTypefaceSpan.java",
"chars": 1211,
"preview": "package uk.co.chrisjenx.calligraphy;\n\nimport android.graphics.Paint;\nimport android.graphics.Typeface;\nimport android.te"
},
{
"path": "calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyUtils.java",
"chars": 13862,
"preview": "package uk.co.chrisjenx.calligraphy;\n\nimport android.content.Context;\nimport android.content.res.AssetManager;\nimport an"
},
{
"path": "calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/HasTypeface.java",
"chars": 786,
"preview": "package uk.co.chrisjenx.calligraphy;\n\nimport android.graphics.Typeface;\n\n/**\n * There are two ways to set typeface for c"
},
{
"path": "calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/ReflectionUtils.java",
"chars": 1668,
"preview": "package uk.co.chrisjenx.calligraphy;\n\nimport android.util.Log;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect"
},
{
"path": "calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/TypefaceUtils.java",
"chars": 2883,
"preview": "package uk.co.chrisjenx.calligraphy;\n\nimport android.content.res.AssetManager;\nimport android.graphics.Typeface;\nimport "
},
{
"path": "calligraphy/src/main/res/values/attrs.xml",
"chars": 107,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <attr name=\"fontPath\" format=\"string\"/>\n</resources>"
},
{
"path": "calligraphy/src/main/res/values/ids.xml",
"chars": 111,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <item name=\"calligraphy_tag_id\" type=\"id\"/>\n</resources>"
},
{
"path": "calligraphy/src/main/res/values/public.xml",
"chars": 106,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <public name=\"fontPath\" type=\"attr\"/>\n</resources>\n"
},
{
"path": "gradle/deploy.gradle",
"chars": 3714,
"preview": "/*\n * Copyright 2013 Chris Banes\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not us"
},
{
"path": "gradle/wrapper/gradle-wrapper.properties",
"chars": 231,
"preview": "#Mon Apr 16 11:48:42 CEST 2018\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER"
},
{
"path": "gradle.properties",
"chars": 1492,
"preview": "# Project-wide Gradle settings.\n\n# IDE (e.g. Android Studio) users:\n# Settings specified in this file will override any "
},
{
"path": "gradlew",
"chars": 5299,
"preview": "#!/usr/bin/env sh\n\n##############################################################################\n##\n## Gradle start up"
},
{
"path": "gradlew.bat",
"chars": 2260,
"preview": "@if \"%DEBUG%\" == \"\" @echo off\r\n@rem ##########################################################################\r\n@rem\r\n@r"
},
{
"path": "settings.gradle",
"chars": 45,
"preview": "include ':calligraphy', ':CalligraphySample'\n"
}
]
// ... and 1 more files (download for full content)
About this extraction
This page contains the full source code of the chrisjenx/Calligraphy GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 49 files (119.9 KB), approximately 29.1k tokens, and a symbol index with 127 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.