태그 보관물: android-fonts

android-fonts

Android-사용자 정의 글꼴 사용 같습니다. Typeface myTypeface

에 맞춤 글꼴을 적용 TextView했지만 서체를 변경하지 않는 것 같습니다.

내 코드는 다음과 같습니다.

    Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/myFont.ttf");
    TextView myTextView = (TextView)findViewById(R.id.myTextView);
    myTextView.setTypeface(myTypeface);

누구 든지이 문제에서 벗어날 수 있습니까?



답변

Mobiletuts +에는 Android 용 텍스트 형식에 대한 훌륭한 자습서가 있습니다. 빠른 팁 : Android 글꼴 사용자 정의

편집 : 지금 직접 테스트했습니다. 해결책은 다음과 같습니다. fonts라는 하위 폴더를 사용할 수 있지만 assets폴더가 아닌 폴더에 있어야 res합니다. 그래서

자산 / 글꼴

또한 글꼴 종료는 글꼴 파일 자체의 끝이 모두 소문자인지 확인하십시오. 즉 그것은 안 myFont.TTF하지만, myfont.ttf 이 방법은 소문자로해야합니다


답변

이 스레드에 설명 된 대부분의 솔루션을 시도한 후 실수로 응용 프로그램에 사용자 정의 글꼴을 쉽게 추가 할 수있는 Christopher Jenkins의 라이브러리 인 Calligraphy ( https://github.com/chrisjenx/Calligraphy )를 발견했습니다 . 여기에 제안 된 접근법과 비교 한 그의 lib의 장점은 다음과 같습니다.

  1. 자체 재정의 된 TextView 구성 요소를 도입 할 필요가 없으며 내장 된 TextView를 사용합니다.
  2. gradle을 사용하여 라이브러리를 쉽게 포함시킬 수 있습니다
  3. 라이브러리는 글꼴 선택을 제한하지 않습니다. 선호하는 것을 자산 디렉토리에 추가하십시오.
  4. 사용자 정의 텍스트보기뿐만 아니라 다른 모든 텍스트 기반 Android 구성 요소도 사용자 정의 글꼴을 사용하여 표시됩니다.

답변

좋은 답변이 이미 있다는 것을 알고 있지만 여기에는 완전히 작동하는 구현이 있습니다.

맞춤 텍스트보기는 다음과 같습니다.

package com.mycompany.myapp.widget;

/**
 * Text view with a custom font.
 * <p/>
 * In the XML, use something like {@code customAttrs:customFont="roboto-thin"}. The list of fonts
 * that are currently supported are defined in the enum {@link CustomFont}. Remember to also add
 * {@code xmlns:customAttrs="http://schemas.android.com/apk/res-auto"} in the header.
 */
public class CustomFontTextView extends TextView {

    private static final String sScheme =
            "http://schemas.android.com/apk/res-auto";
    private static final String sAttribute = "customFont";

    static enum CustomFont {
        ROBOTO_THIN("fonts/Roboto-Thin.ttf"),
        ROBOTO_LIGHT("fonts/Roboto-Light.ttf");

        private final String fileName;

        CustomFont(String fileName) {
            this.fileName = fileName;
        }

        static CustomFont fromString(String fontName) {
            return CustomFont.valueOf(fontName.toUpperCase(Locale.US));
        }

        public Typeface asTypeface(Context context) {
            return Typeface.createFromAsset(context.getAssets(), fileName);
        }
    }

    public CustomFontTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        if (isInEditMode()) {
            return;
        } else {
            final String fontName = attrs.getAttributeValue(sScheme, sAttribute);

            if (fontName == null) {
                throw new IllegalArgumentException("You must provide \"" + sAttribute + "\" for your text view");
            } else {
                final Typeface customTypeface = CustomFont.fromString(fontName).asTypeface(context);
                setTypeface(customTypeface);
            }
        }
    }
}

맞춤 속성은 다음과 같습니다. res/attrs.xml파일 로 이동해야 합니다.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomFontTextView">
        <attr name="customFont" format="string"/>
    </declare-styleable>
</resources>

사용 방법은 다음과 같습니다. 상대 레이아웃을 사용하여 줄 바꿈하고 customAttr선언을 표시 하지만 이미 존재하는 레이아웃 일 수 있습니다.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:customAttrs="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.mycompany.myapp.widget.CustomFontTextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="foobar"
         customAttrs:customFont="roboto_thin" />

</RelativeLayout>


답변

나는 이것을 전에 성공적으로 사용했다. 우리 구현의 유일한 차이점은 자산에 하위 폴더를 사용하지 않았다는 것입니다. 그래도 변경 될지 확실하지 않습니다.


답변

글꼴을 올바른 위치에 배치하고 글꼴 파일 자체에 오류가없는 경우 코드는 RATTLESNAKE와 같이 작동합니다.

그러나 레이아웃 xml에서 글꼴을 다음과 같이 정의 할 수 있다면 훨씬 쉬울 것입니다.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <!-- This text view is styled with the app theme -->
    <com.innovattic.font.FontTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This uses my font in bold italic style" />

    <!-- This text view is styled here and overrides the app theme -->
    <com.innovattic.font.FontTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:flFont="anotherFont"
        android:textStyle="normal"
        android:text="This uses another font in normal style" />

    <!-- This text view is styled with a style and overrides the app theme -->
    <com.innovattic.font.FontTextView
        style="@style/StylishFont"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This also uses another font in normal style" />

</LinearLayout>

함께 res/values/styles.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">

    <!-- Application theme -->
    <!-- Use a different parent if you don't want Holo Light -->
    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
        <item name="android:textViewStyle">@style/MyTextViewStyle</item>
    </style>

    <!-- Style to use for ALL text views (including FontTextView) -->
    <!-- Use a different parent if you don't want Holo Light -->
    <style name="MyTextViewStyle" parent="@android:style/Widget.Holo.Light.TextView">
        <item name="android:textAppearance">@style/MyTextAppearance</item>
    </style>

    <!-- Text appearance to use for ALL text views (including FontTextView) -->
    <!-- Use a different parent if you don't want Holo Light -->
    <style name="MyTextAppearance" parent="@android:style/TextAppearance.Holo">
        <!-- Alternatively, reference this font with the name "aspergit" -->
        <!-- Note that only our own TextView's will use the font attribute -->
        <item name="flFont">someFont</item>
        <item name="android:textStyle">bold|italic</item>
    </style>

    <!-- Alternative style, maybe for some other widget -->
    <style name="StylishFont">
        <item name="flFont">anotherFont</item>
        <item name="android:textStyle">normal</item>
    </style>

</resources>

이 목적을 위해 특별히 몇 가지 도구를 만들었습니다. GitHub 에서이 프로젝트 를 참조 하거나 전체 내용을 설명하는 이 블로그 게시물 을 살펴보십시오 .


답변

안드로이드 O의 프리뷰 버전에서 그것을 할 수있는 가장 좋은 방법은이 방법이다 :

그것은 당신이 안드로이드 스튜디오 2.4 이상이있는 경우에만 작동합니다

  1. 마우스 오른쪽 버튼을 클릭하면 폴더 고해상도을 하고 이동 새로 만들기> 안드로이드 자원 디렉토리 . New
    Resource Directory 창이 나타납니다.
  2. 리소스 종류 목록에서 font 를 선택한 다음 확인을 클릭합니다.
  3. 글꼴 폴더에 글꼴 파일을 추가합니다 아래 생성 국지적 인 폴더 구조 R.font.dancing_script, R.font.la_laR.font.ba_ba.
  4. 글꼴 파일을 두 번 클릭 하여 편집기에서 파일의 글꼴을 미리 봅니다.

다음으로 폰트 패밀리를 만들어야합니다 :

  1. 글꼴 폴더를 마우스 오른쪽 단추로 클릭하고 새로 작성> 글꼴 자원 파일 로 이동 하십시오 . 새 리소스 파일 창이 나타납니다.
  2. 파일 이름을 입력 한 다음 확인을 클릭하십시오 . 새 글꼴 리소스 XML이 편집기에서 열립니다.
  3. 각 글꼴 파일, 스타일 및 가중치 속성을 글꼴 태그 요소로 묶습니다. 다음 XML은 글꼴 자원 XML에 글꼴 관련 속성을 추가하는 방법을 보여줍니다.

TextView에 글꼴 추가하기 :

   <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/hey_fontfamily"/>

설명서에서와 같이

폰트로 작업하기

모든 단계가 정확합니다.


답변

android의 사용자 정의 글꼴의 경우 자산 폴더 이름 내에 폴더를 작성하십시오. “fonts”원하는 fonts.ttf 또는 .otf 파일을 저장하십시오.

UIBaseFragment를 확장하는 경우 :

Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Arial.ttf");
        tv.setTypeface(font);

그렇지 않으면 활동을 확장하는 경우 :

Typeface font = Typeface.createFromAsset(getContext().getAssets(), "fonts/Arial.ttf");
        tv.setTypeface(font);