Java 코드에서 "android : fontFamily ="sans-serif-light "에 해당하는 것은 무엇입니까?


106

내 질문은 아주 간단합니다.

모든 텍스트 뷰에서 현재 속성을 사용하고 있습니다.

android:fontFamily="sans-serif-light"

포스트 HC 장치에 멋진 모습을 제공합니다.

불행히도 이것은 모든 위젯에서 작동하지 않으며 내 Spinner의 경우 어댑터를 덮어 써야합니다.

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    //You can use the new tf here.

    if(convertView == null || convertView.getTag() == null) {
        // new view - populate 
        convertView = inflater.inflate(android.R.layout.simple_spinner_dropdown_item, parent, false);
        convertView.setTag(new Object());
    }

    CheckedTextView spinner_text=(CheckedTextView) convertView.findViewById(android.R.id.text1);
    //Typeface should be set here...
    return spinner_text;
    }
}

그렇다면 코드로 정확히 동일한 결과를 얻을 수있는 방법이 있습니까?

추신 : 아니요, 자산 폴더에 서체를 넣지 않고 시스템 1을 사용하고 싶습니다.

답변:


168

setTypeface()Typeface.create()다음 과 함께 가능해야합니다 .

convertView.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL));

문서 보기 :

패밀리 이름 및 옵션 스타일 정보가 지정된 서체 개체를 만듭니다. 이름에 null이 전달되면 "기본"글꼴이 선택됩니다. 결과적인 서체 객체를 쿼리 ( getStyle())하여 "실제"스타일 특성이 무엇인지 알아낼 수 있습니다 .

이 주석Typeface.create() 에서 언급했듯이 과도하게 사용하면 메모리에 좋지 않습니다 . 제안 해시 테이블은 좋은 솔루션입니다,하지만 당신은 그에게 당신이 자산에서 서체를 생성하지 않기 때문에 조금 수정해야합니다.


2
스피너 항목이 많은 경우 메모리 문제에 유의하십시오. 내 답변을 약간 업데이트했습니다.
saschoar

44

Android 4.1 (API 레벨 16) 및 지원 라이브러리 26 이상

res-> font 폴더를 사용하는 경우 다음과 같이 사용할 수 있습니다.

  val typeface = ResourcesCompat.getFont(Context, R.font.YOUR_FONT)
  TextView.setTypeface(typeface)

20

제 생각에는 메모리 문제없이 TextView에 프로그래밍 방식으로 시스템 글꼴을 적용하는 방법이 있으며 방법을 사용하고 있습니다 textview.setTextAppearance.

<style name="styleA">
    <item name="android:fontFamily">sans-serif</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textColor">?android:attr/textColorPrimary</item>
</style>
<style name="styleB">
    <item name="android:fontFamily">sans-serif-light</item>
    <item name="android:textStyle">normal</item>
    <item name="android:textColor">?android:attr/textColorTertiary</item>
</style>


if(condition){
    textView.setTextAppearance(context,R.style.styleA);
}else{
    textView.setTextAppearance(context,R.style.styleB);
}

2
android:fontFamilyAPI 16이 필요합니다.
CoolMind

2
사용 TextViewCompat.setTextAppearance(textView, R.style.styleA).
CoolMind

19

이를 사용하여 xml의 android : fontFamily와 유사한 fontfamily를 동적으로 설정할 수 있습니다.

For Custom font:

 TextView tv = ((TextView) v.findViewById(R.id.select_item_title));
 Typeface face=Typeface.createFromAsset(getAssets(),"fonts/mycustomfont.ttf"); 
 tv.setTypeface(face);

For Default font:

 tv.setTypeface(Typeface.create("sans-serif-medium",Typeface.NORMAL));

사용되는 기본 글꼴 모음 목록입니다 . 큰 따옴표 문자열 "sans-serif-medium" 을 대체하여이 중 하나를 사용하십시오.

FONT FAMILY                    TTF FILE                    

1  casual                      ComingSoon.ttf              
2  cursive                     DancingScript-Regular.ttf   
3  monospace                   DroidSansMono.ttf           
4  sans-serif                  Roboto-Regular.ttf          
5  sans-serif-black            Roboto-Black.ttf            
6  sans-serif-condensed        RobotoCondensed-Regular.ttf 
7  sans-serif-condensed-light  RobotoCondensed-Light.ttf   
8  sans-serif-light            Roboto-Light.ttf            
9  sans-serif-medium           Roboto-Medium.ttf           
10  sans-serif-smallcaps       CarroisGothicSC-Regular.ttf 
11  sans-serif-thin            Roboto-Thin.ttf             
12  serif                      NotoSerif-Regular.ttf       
13  serif-monospace            CutiveMono.ttf              

"mycustomfont.ttf"는 ttf 파일입니다. 경로src / assets / fonts / mycustomfont.ttf에 있으며이 기본 글꼴 패밀리 에서 기본 글꼴에 대한 자세한 내용을 참조 할 수 있습니다.


13

옵션 1 -API 26 이상

// Jave
Typeface typeface = getResources().getFont(R.font.myfont);
textView.setTypeface(typeface);

// Kotlin
val typeface = resources.getFont(R.font.myfont)
textView.typeface = typeface

옵션 2 -API 16 이상

// Java
Typeface typeface = ResourcesCompat.getFont(context, R.font.myfont);

// Kotlin
val typeface = ResourcesCompat.getFont(context, R.font.myfont)

Android 개발자 가이드 에서 전체 만료를 확인하세요 .


6

사용하면 가능합니다.

setTypeface(Typeface tf, int style)TextView수업 방법 .

spinner_text.setTypeface(Typeface.SANS_SERIF,Typeface.NORMAL);

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.