Как изменить шрифт в XML-файле android studio - PullRequest
0 голосов
/ 01 июня 2018

Я создал папку со шрифтами, добавил свой шрифт (Tilitium Bold) и как изменить шрифт моей кнопки.

Я пробовал с android:fontFamily="@font/Titilum-Bold", но он не работает.Есть идеи?

Ответы [ 2 ]

0 голосов
/ 01 июня 2018

Включить следующий класс в ваш проект

public class FontManager {

    private static FontManager sInstance;
    private HashMap<String, Typeface> mFontCache = new HashMap<>(); // <path to the font file in the assets folder, cached Typeface>

    /**
     * Gets the FontManager singleton
     *
     * @return the FontManager singleton
     */
    public static FontManager getInstance() {
        if (sInstance == null) {
            sInstance = new FontManager();
        }
        return sInstance;
    }

    /**
     * Gets a Typeface from the cache. If the Typeface does not exist, creates it, cache it and returns it.
     *
     * @param context a Context
     * @param path    Path to the font file in the assets folder. ie "fonts/MyCustomFont.ttf"
     * @return the corresponding Typeface (font)
     * @throws RuntimeException if the font asset is not found
     */
    public Typeface getTypeface(Context context, String path) throws RuntimeException {
        Typeface typeface = mFontCache.get(path);
        if (typeface == null) {
            try {
                typeface = Typeface.createFromAsset(context.getAssets(), "fonts/" +path);
            } catch (RuntimeException exception) {
                String message = "Font assets/" + path + " cannot be loaded";
                throw new RuntimeException(message);
            }
            mFontCache.put(path, typeface);
        }
        return typeface;
    }

    /**
     * Gets a Typeface from the cache. If the Typeface does not exist, creates it, cache it and returns it.
     *
     * @param context   a Context
     * @param pathResId String resource id for the path to the font file in the assets folder. ie "fonts/MyCustomFont.ttf"
     * @return the corresponding Typeface (font)
     * @throws RuntimeException if the resource or the font asset is not found
     */
    public Typeface getTypeface(Context context, int pathResId) throws RuntimeException {
        try {
            String path = context.getResources().getString(pathResId);
            return getTypeface(context, path);
        } catch (Resources.NotFoundException exception) {
            String message = "String resource id " + pathResId + " not found";
            throw new RuntimeException(message);
        }
    }

    /**
     * Applies a font to a TextView that uses the "fontPath" attribute.
     *
     * @param textView TextView when the font should apply
     * @param attrs    Attributes that contain the "fontPath" attribute with the path to the font file in the assets folder
     */
    public void applyFont(TextView textView, AttributeSet attrs) {
        if (attrs != null) {
            Context context = textView.getContext();
            TypedArray styledAttributes = context.getTheme().obtainStyledAttributes(attrs, R.styleable.customTextView, 0, 0);
            String fontPath = styledAttributes.getString(R.styleable.customTextView_fontFamily);
            if (!TextUtils.isEmpty(fontPath)) {
                Typeface typeface = getTypeface(context, fontPath);
                if (typeface != null) {
                    textView.setTypeface(typeface);
                }
            }
            styledAttributes.recycle();
        }
    }
}

Добавить атрибуты в Res> Значения> Файл атрибутов

 <declare-styleable name="customTextView">
        <attr name="fontFamily" format="string" />
 </declare-styleable>

Создайте виджет, для которого вы хотите изменить шрифты: скажем, CustomTextView

public class CustomTextView extends AppCompatButton {

        public CustomTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
            applyDefaultFont(context);
            FontManager.getInstance().applyFont(this, attrs);
        }

        private void applyDefaultFont(Context context) {
            Typeface typeface = FontManager.getInstance().getTypeface(context, context.getString(R.string.font_regular));
            if (typeface != null) {
                this.setTypeface(typeface);
            }
        }

    }

XML-файл Код:

<com.yourpackage.CustomButton
                android:id="@+id/btnSubmit"
                android:layout_width="match_parent"
                android:layout_height="?actionBarSize"
                android:layout_marginTop="@dimen/_16sdp"
                android:background="@drawable/shape_button_green"
                android:text="@string/submit"
                android:textAllCaps="true"
                android:textColor="@color/white"
                android:textSize="@dimen/font_button"
                app:fontFamily="@string/font_bold" />

Примечание. Если вы копируете полный код, требуемый шрифт должен находиться в папке assets> fonts.

Определить строку для имени нужного шрифта, например:

<string name="font_regular">SF-Pro-Text-Regular.otf</string>
<string name="font_bold">SF-Pro-Text-Bold.otf</string>
0 голосов
/ 01 июня 2018

Как предположил Джей Туммар, я переименовал свой шрифт без пробелов и только строчных букв, и это сработало.

...