Android: Crouton lib и пользовательский шрифт

Я использую пользовательские шрифты в своем приложении, поэтому мне нужен собственный шрифт для Crouton. Я пытался сделать это с помощью setTextAppearance, это не сработало.

<?xml version="1.0" encoding="utf-8"?>
<com.ecab.ui.custom.TextViewCustomFont
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res/com.crouton"
    android:id="@+id/crouton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/ban_confirmation"
    android:gravity="center"
    android:text="TEST"
    android:textColor="@android:color/white"
    custom:typeface="gothamBold" />

На уроке стиля:

INFOCUSTOM = new Builder().setDuration(3000).setTextAppearance(R.id.crouton).build();

Затем я попытался сделать это, изменив setTypeface() на свой шрифт, но это не сработало.

В классе крутонов:

private TextView initializeTextView(final Resources resources) {
TextView text = new TextView(this.activity);
    text.setId(TEXT_ID);
    text.setText(this.text);
    text.setTypeface(MyFonts.getGothamBookBold(this.activity));
    Log.d(Constants.D_TAG, "chaneg the typeFace");
    text.setGravity(this.style.gravity);
    // set the text color if set
    if (this.style.textColorResourceId != 0) {
      text.setTextColor(resources.getColor(this.style.textColorResourceId));
    }

    // Set the text size. If the user has set a text size and text
    // appearance, the text size in the text appearance
    // will override this.
    if (this.style.textSize != 0) {
      text.setTextSize(TypedValue.COMPLEX_UNIT_SP, this.style.textSize);
    }

    // Setup the shadow if requested
    if (this.style.textShadowColorResId != 0) {
      initializeTextViewShadow(resources, text);
    }

    // Set the text appearance
    if (this.style.textAppearanceResId != 0) {
      text.setTextAppearance(this.activity, this.style.textAppearanceResId);
    }
    return text;
  }

Что я могу сделать, чтобы иметь собственный шрифт?

PS: версия библиотеки ==> 1.7


person mrroboaat    schedule 20.04.2013    source источник
comment
Этот ответ может помочь.   -  person iTurki    schedule 21.04.2013
comment
Вы пробовали то, что предложил создатель здесь: stackoverflow.com/a/15223451/644669   -  person Zakaria    schedule 21.04.2013
comment
Ага ! Я знаю эту проблему, но она не работает...   -  person mrroboaat    schedule 21.04.2013
comment
возможный дубликат Использование пользовательских макетов для библиотеки гренок   -  person keyboardsurfer    schedule 22.04.2013
comment
@aat Как вы редактируете файл Crouton.class? Он заблокирован в build/intermediates/exploded-aar/de-key..../crouton/1.8.5/classes.jar   -  person ono    schedule 21.05.2015
comment
Библиотека @ono имеет открытый исходный код, поэтому вы можете изменять исходные коды и добавлять их в свой проект.   -  person mrroboaat    schedule 24.05.2015


Ответы (3)


Хорошо, я нашел проблему!

Он работает со вторым решением, изменяя шрифт. Я просто забыл удалить

setTextAppearance(R.id.crouton)

в классе Стиль. Итак, мой собственный стиль выглядит так:

INFOCUSTOM = new Builder().setDuration(3000).setBackgroundDrawable(R.drawable.ban_confirmation).setHeight(LayoutParams.WRAP_CONTENT)
          .build();

Одна проблема решается, другая приходит :) ! При рисовании фона текст не центрируется по вертикали.

person mrroboaat    schedule 21.04.2013

Вы можете создать собственный стиль, который использует resourceId вашего внешнего вида текста с помощью Style.Builder.setTextAppearance(...).

Это берет ссылку из вашего styles.xml и использует ее во внутреннем TextView Crouton.

Затем вы можете вызвать Crouton.makeText или Crouton.showText со своим собственным стилем.

Источник

person Zakaria    schedule 20.04.2013

Как выглядит MyFonts.getGothamBookBold()?

Однако это должно работать:

  private TextView initializeTextView(final Resources resources) {
    TextView text = new TextView(this.activity);
    text.setId(TEXT_ID);
    text.setText(this.text);
    Typeface myTypeFace = Typeface.createFromAsset(this.activity.getAssets(), "gothamBold.ttf"); 
    text.setTypeface(myTypeFace);
    text.setGravity(this.style.gravity);

    // set the text color if set
    if (this.style.textColorResourceId != 0) {
      text.setTextColor(resources.getColor(this.style.textColorResourceId));
    }
person Ahmad    schedule 20.04.2013
comment
У меня есть класс для управления моими пользовательскими шрифтами следующим образом: public static Typeface getGothamBookBold(Context ctx) { return Typeface.createFromAsset(ctx.getAssets(), BASE + "Gotham-Bold.otf"); } - person mrroboaat; 21.04.2013
comment
Как вы редактируете файл Crouton.class? Он заблокирован в build/intermediates/exploded-aar/de-key..../crouton/1.8.5/classes.jar - person ono; 21.05.2015
comment
@ono Я не уверен, что понял твой вопрос. Я не редактирую исходный код Crouton. - person Ahmad; 21.05.2015
comment
@ Ахмад, разве ты не редактируешь метод initializeTextView в Crouton.class? - person ono; 21.05.2015
comment
@ono А, извини. Я не смотрел на контекст вопроса. Я ответил на этот вопрос два года назад и не мог вспомнить, что ОП просил пользовательскую версию Крастона. По сути, вам нужно вместо того, чтобы добавлять Crouton в качестве зависимости через gradle, добавить его как модуль и самостоятельно изменить исходный код. Я только что проверил, и похоже, что Crouton по-прежнему не поддерживает пользовательские шрифты, так что это одно из возможных решений. Пожалуй, самый прямой. - person Ahmad; 21.05.2015