Android에서 글꼴을 변경하는 방법 TextView 제품군
그래서 저는 그것을 바꾸고 싶습니다.android:fontFamily
Android에서는 사전 정의된 글꼴이 없습니다.미리 정의된 항목 중 하나를 선택하려면 어떻게 해야 합니까?나만의 TypeFace를 정의할 필요는 없지만 지금 보여주는 것과 다른 것만 있으면 됩니다.
<TextView
android:id="@+id/HeaderText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp"
android:gravity="center"
android:text="CallerBlocker"
android:textSize="40dp"
android:fontFamily="Arial"
/>
한안 될 것 요! 내거한일정효없것같다니습! BTW.android:fontFamily="Arial"
멍청한 시도였어요!
Android 4.1 / 4.2 / 5.0부터는 다음과 같은 Roboto 글꼴 제품군을 사용할 수 있습니다.
android:fontFamily="sans-serif" // roboto regular
android:fontFamily="sans-serif-light" // roboto light
android:fontFamily="sans-serif-condensed" // roboto condensed
android:fontFamily="sans-serif-black" // roboto black
android:fontFamily="sans-serif-thin" // roboto thin (android 4.2)
android:fontFamily="sans-serif-medium" // roboto medium (android 5.0)
와 결합하여
android:textStyle="normal|bold|italic"
다음 16가지 변형이 가능합니다.
- 로보토 레귤러
- 로봇 이탤릭체
- 굵게 표시된 로봇
- 로보토 굵은 기울임꼴
- 로보토 라이트
- 로봇-라이트 이탤릭체
- Roboto-thin
- Roboto-Thin 이탤릭체
- 로봇 응축
- 로봇 축약 기울임꼴
- 로봇 응축 볼드
- 로봇 축약 굵은 기울임꼴
- 로보토블랙
- 로봇-검은색 기울임꼴
- 로봇 - 중형
- 로보토-중간 이탤릭체
fonts.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="font_family_light">sans-serif-light</string>
<string name="font_family_medium">sans-serif-medium</string>
<string name="font_family_regular">sans-serif</string>
<string name="font_family_condensed">sans-serif-condensed</string>
<string name="font_family_black">sans-serif-black</string>
<string name="font_family_thin">sans-serif-thin</string>
</resources>
Android-Studio 3.0부터는 글꼴 제품군을 매우 쉽게 변경할 수 있습니다.
지원 라이브러리 26을 사용하여 Android API 버전 16 이상을 실행하는 장치에서 작동합니다.
font
res
원하는 하여 내부에 붙여넣습니다.font
폴더를 누릅니다.와 같은 .
참고: Android Support Library 26.0 이후에는 API 26 이하를 실행하는 장치에서 글꼴을 로드하려면 두 가지 속성 집합( Android: 및 app: )을 모두 선언해야 합니다.
이제 다음을 사용하여 레이아웃의 글꼴을 변경할 수 있습니다.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/dancing_script"
app:fontFamily="@font/dancing_script"/>
프로그래밍 방식으로 변경하려면
Typeface typeface = getResources().getFont(R.font.myfont);
//or to support all versions use
Typeface typeface = ResourcesCompat.getFont(context, R.font.myfont);
textView.setTypeface(typeface);
styles.xml을 사용하여 글꼴을 변경하려면 스타일을 작성합니다.
<style name="Regular">
<item name="android:fontFamily">@font/dancing_script</item>
<item name="fontFamily">@font/dancing_script</item>
<item name="android:textStyle">normal</item>
</style>
그리고 이 스타일을 적용합니다.TextView
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/Regular"/>
자신만의 글꼴 패밀리를 만들 수도 있습니다.
글꼴 폴더를 마우스 오른쪽 단추로 클릭하고 새로 만들기 > 글꼴 리소스 파일로 이동합니다.새 리소스 파일 창이 나타납니다.
파일 이름을 입력한 후 [확인]을 누릅니다.새 글꼴 리소스 XML이 편집기에서 열립니다.
예를 들어, 여기에 자신의 글꼴 패밀리를 작성합니다.
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
<font
android:fontStyle="normal"
android:fontWeight="400"
android:font="@font/lobster_regular" />
<font
android:fontStyle="italic"
android:fontWeight="400"
android:font="@font/lobster_italic" />
</font-family>
이것은 단순히 특정 글꼴Style 및 fontWeight를 해당 변형을 렌더링하는 데 사용할 글꼴 리소스에 매핑하는 것입니다.fontStyle의 유효한 값은 일반 또는 기울임꼴이며, fontWeight는 CSS 글꼴-가중치 규격을 따릅니다.
레이아웃에서 글꼴 패밀리를 변경하려면 작성할 수 있습니다.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/lobster"/>
프로그래밍 방식으로 변경하려면
Typeface typeface = getResources().getFont(R.font.lobster);
//or to support all versions use
Typeface typeface = ResourcesCompat.getFont(context, R.font.lobster);
textView.setTypeface(typeface);
전체 앱의 글꼴을 변경하려면앱테마에서 이 두 줄을 추가합니다.
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:fontFamily">@font/your_font</item>
<item name="fontFamily">@font/your_font</item>
</style>
자세한 내용은 설명서의 Android 사용자 지정 글꼴 튜토리얼을 참조하십시오.
다음은 글꼴을 프로그래밍 방식으로 설정하는 방법입니다.
TextView tv = (TextView) findViewById(R.id.appname);
Typeface face = Typeface.createFromAsset(getAssets(),
"fonts/epimodem.ttf");
tv.setTypeface(face);
글꼴 파일을 자산 폴더에 넣습니다.저의 경우 글꼴이라는 하위 디렉터리를 만들었습니다.
편집: 자산 폴더의 위치가 궁금한 경우 이 질문을 참조하십시오.
나는 해석해야 했습니다./system/etc/fonts.xml
롤리팝의 입니다.다음은 롤리팝의 현재 글꼴 계열입니다.
╔════╦════════════════════════════╦═════════════════════════════╗
║ ║ 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 ║
╚════╩════════════════════════════╩═════════════════════════════╝
다음은 파서(FontListParser를 기반으로 함)입니다.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.util.Xml;
/**
* Helper class to get the current font families on an Android device.</p>
*
* Usage:</p> {@code List<SystemFont> fonts = FontListParser.safelyGetSystemFonts();}</p>
*/
public final class FontListParser {
private static final File FONTS_XML = new File("/system/etc/fonts.xml");
private static final File SYSTEM_FONTS_XML = new File("/system/etc/system_fonts.xml");
public static List<SystemFont> getSystemFonts() throws Exception {
String fontsXml;
if (FONTS_XML.exists()) {
fontsXml = FONTS_XML.getAbsolutePath();
} else if (SYSTEM_FONTS_XML.exists()) {
fontsXml = SYSTEM_FONTS_XML.getAbsolutePath();
} else {
throw new RuntimeException("fonts.xml does not exist on this system");
}
Config parser = parse(new FileInputStream(fontsXml));
List<SystemFont> fonts = new ArrayList<>();
for (Family family : parser.families) {
if (family.name != null) {
Font font = null;
for (Font f : family.fonts) {
font = f;
if (f.weight == 400) {
break;
}
}
SystemFont systemFont = new SystemFont(family.name, font.fontName);
if (fonts.contains(systemFont)) {
continue;
}
fonts.add(new SystemFont(family.name, font.fontName));
}
}
for (Alias alias : parser.aliases) {
if (alias.name == null || alias.toName == null || alias.weight == 0) {
continue;
}
for (Family family : parser.families) {
if (family.name == null || !family.name.equals(alias.toName)) {
continue;
}
for (Font font : family.fonts) {
if (font.weight == alias.weight) {
fonts.add(new SystemFont(alias.name, font.fontName));
break;
}
}
}
}
if (fonts.isEmpty()) {
throw new Exception("No system fonts found.");
}
Collections.sort(fonts, new Comparator<SystemFont>() {
@Override
public int compare(SystemFont font1, SystemFont font2) {
return font1.name.compareToIgnoreCase(font2.name);
}
});
return fonts;
}
public static List<SystemFont> safelyGetSystemFonts() {
try {
return getSystemFonts();
} catch (Exception e) {
String[][] defaultSystemFonts = {
{
"cursive", "DancingScript-Regular.ttf"
}, {
"monospace", "DroidSansMono.ttf"
}, {
"sans-serif", "Roboto-Regular.ttf"
}, {
"sans-serif-light", "Roboto-Light.ttf"
}, {
"sans-serif-medium", "Roboto-Medium.ttf"
}, {
"sans-serif-black", "Roboto-Black.ttf"
}, {
"sans-serif-condensed", "RobotoCondensed-Regular.ttf"
}, {
"sans-serif-thin", "Roboto-Thin.ttf"
}, {
"serif", "NotoSerif-Regular.ttf"
}
};
List<SystemFont> fonts = new ArrayList<>();
for (String[] names : defaultSystemFonts) {
File file = new File("/system/fonts", names[1]);
if (file.exists()) {
fonts.add(new SystemFont(names[0], file.getAbsolutePath()));
}
}
return fonts;
}
}
/* Parse fallback list (no names) */
public static Config parse(InputStream in) throws XmlPullParserException, IOException {
try {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(in, null);
parser.nextTag();
return readFamilies(parser);
} finally {
in.close();
}
}
private static Alias readAlias(XmlPullParser parser) throws XmlPullParserException, IOException {
Alias alias = new Alias();
alias.name = parser.getAttributeValue(null, "name");
alias.toName = parser.getAttributeValue(null, "to");
String weightStr = parser.getAttributeValue(null, "weight");
if (weightStr == null) {
alias.weight = 0;
} else {
alias.weight = Integer.parseInt(weightStr);
}
skip(parser); // alias tag is empty, ignore any contents and consume end tag
return alias;
}
private static Config readFamilies(XmlPullParser parser) throws XmlPullParserException,
IOException {
Config config = new Config();
parser.require(XmlPullParser.START_TAG, null, "familyset");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
if (parser.getName().equals("family")) {
config.families.add(readFamily(parser));
} else if (parser.getName().equals("alias")) {
config.aliases.add(readAlias(parser));
} else {
skip(parser);
}
}
return config;
}
private static Family readFamily(XmlPullParser parser) throws XmlPullParserException,
IOException {
String name = parser.getAttributeValue(null, "name");
String lang = parser.getAttributeValue(null, "lang");
String variant = parser.getAttributeValue(null, "variant");
List<Font> fonts = new ArrayList<Font>();
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String tag = parser.getName();
if (tag.equals("font")) {
String weightStr = parser.getAttributeValue(null, "weight");
int weight = weightStr == null ? 400 : Integer.parseInt(weightStr);
boolean isItalic = "italic".equals(parser.getAttributeValue(null, "style"));
String filename = parser.nextText();
String fullFilename = "/system/fonts/" + filename;
fonts.add(new Font(fullFilename, weight, isItalic));
} else {
skip(parser);
}
}
return new Family(name, fonts, lang, variant);
}
private static void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
int depth = 1;
while (depth > 0) {
switch (parser.next()) {
case XmlPullParser.START_TAG:
depth++;
break;
case XmlPullParser.END_TAG:
depth--;
break;
}
}
}
private FontListParser() {
}
public static class Alias {
public String name;
public String toName;
public int weight;
}
public static class Config {
public List<Alias> aliases;
public List<Family> families;
Config() {
families = new ArrayList<Family>();
aliases = new ArrayList<Alias>();
}
}
public static class Family {
public List<Font> fonts;
public String lang;
public String name;
public String variant;
public Family(String name, List<Font> fonts, String lang, String variant) {
this.name = name;
this.fonts = fonts;
this.lang = lang;
this.variant = variant;
}
}
public static class Font {
public String fontName;
public boolean isItalic;
public int weight;
Font(String fontName, int weight, boolean isItalic) {
this.fontName = fontName;
this.weight = weight;
this.isItalic = isItalic;
}
}
public static class SystemFont {
public String name;
public String path;
public SystemFont(String name, String path) {
this.name = name;
this.path = path;
}
}
}
프로젝트에서 위의 클래스를 자유롭게 사용하십시오.예를 들어 사용자에게 글꼴 패밀리를 선택하고 사용자의 기본 설정에 따라 글꼴을 설정할 수 있습니다.
불완전한 작은 예:
final List<FontListParser.SystemFont> fonts = FontListParser.safelyGetSystemFonts();
String[] items = new String[fonts.size()];
for (int i = 0; i < fonts.size(); i++) {
items[i] = fonts.get(i).name;
}
new AlertDialog.Builder(this).setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
FontListParser.SystemFont selectedFont = fonts.get(which);
// TODO: do something with the font
Toast.makeText(getApplicationContext(), selectedFont.path, Toast.LENGTH_LONG).show();
}
}).show();
Android에서는 XML 레이아웃에서 사용자 지정 글꼴을 설정할 수 없습니다.대신 특정 글꼴 파일을 앱의 자산 폴더에 번들로 묶어서 프로그래밍 방식으로 설정해야 합니다.다음과 같은 것:
TextView textView = (TextView) findViewById(<your TextView ID>);
Typeface typeFace = Typeface.createFromAsset(getAssets(), "<file name>");
textView.setTypeface(typeFace);
setContentView()가 호출된 후에만 이 코드를 실행할 수 있습니다.또한일에글 Android서지원다합같니다아야음과부며되꼴만으로 되어 합니다..ttf (TrueType)
또는.otf (OpenType)
서식을 정하다그래도 일부 글꼴은 작동하지 않을 수 있습니다.
이 글꼴은 Android에서 사용할 수 있는 글꼴로, Android에서 글꼴 파일을 지원하지 않는 경우 이 글꼴을 사용하여 코드가 작동 중인지 확인할 수 있습니다.
Android O 업데이트:Roger의 말에 따르면, 이것은 이제 Android O의 XML에서 가능합니다.
Kotlin 코드 - 리소스 폴더에서 사용자 정의 글꼴을 설정하는 텍스트 보기
res -> font -> avenir_next_regular.ttf에서 사용자 지정 글꼴 설정
textView!!.typeface = ResourcesCompat.getFont(context!!, R.font.avenir_next_regular)
로봇을 프로그래밍 방식으로 설정하려면:
paint.setTypeface(Typeface.create("sans-serif-thin", Typeface.NORMAL));
프로그램적으로 원한다면, 당신은 그것을 사용할 수 있습니다.
label.setTypeface(Typeface.SANS_SERIF, Typeface.ITALIC);
에▁where디SANS_SERIF
사용할 수 있는 항목:
DEFAULT
DEFAULT_BOLD
MONOSPACE
SANS_SERIF
SERIF
그리고 어디서ITALIC
사용할 수 있는 항목:
BOLD
BOLD_ITALIC
ITALIC
NORMAL
Android Developers에 모두 명시되어 있습니다.
은 같다니습과 android:typeface
.
내장 글꼴은 다음과 같습니다.
- 보통의
- 산스
- 세리프
- 단일 공간
Typeface typeface = ResourcesCompat.getFont(context, R.font.font_name);
textView.setTypeface(typeface);
의 떤것든쉽써넣다게이어▁▁any에 쉽게 글꼴을 합니다.textview
res
> 님의 디렉토리입니다.
한 가지 간단한 방법은 프로젝트에 원하는 글꼴을 추가하는 것입니다.
파일로 이동 ->새로 만들기 ->새 리소스 디렉터리 글꼴 선택
리소스에 새 디렉터리, 글꼴을 만듭니다.
글꼴(.ttf)을 다운로드합니다.저는 같은 용도로 https://fonts.google.com 을 사용합니다.
글꼴 폴더에 추가한 다음 XML 또는 프로그래밍 방식으로 글꼴을 사용합니다.
XML -
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/your_font"/>
프로그램적으로 -
Typeface typeface = ResourcesCompat.getFont(this, R.font.your_font);
textView.setTypeface(typeface);
제가 너무 늦었다고 생각하지만 이 해결책이 다른 사람들에게 도움이 될 수도 있습니다.사용자 정의 글꼴을 사용하려면 글꼴 디렉터리에 글꼴 파일을 놓습니다.
textView.setTypeface(ResourcesCompat.getFont(this, R.font.lato));
저는 당신이 안드로이드 애플리케이션에서 사용자 정의 글꼴을 사용할 수 있도록 설계된 크리스 젱스의 훌륭한 라이브러리 캘리그라피를 사용하고 있습니다.한 번 해보세요!
당신이 원하는 것은 불가능합니다..TypeFace
당신의 법전에서.
XML
이 할 수 은 당이할수있것입니다.
android:typeface="sans" | "serif" | "monospace"
그렇지 않으면 XML 글꼴로 많이 재생할 수 없습니다.:)
위해서Arial
코드에 활자 모양을 설정해야 합니다.
글꼴을 관리하는 쉬운 방법은 리소스를 통해 다음과 같이 선언하는 것입니다.
<!--++++++++++++++++++++++++++-->
<!--added on API 16 (JB - 4.1)-->
<!--++++++++++++++++++++++++++-->
<!--the default font-->
<string name="fontFamily__roboto_regular">sans-serif</string>
<string name="fontFamily__roboto_light">sans-serif-light</string>
<string name="fontFamily__roboto_condensed">sans-serif-condensed</string>
<!--+++++++++++++++++++++++++++++-->
<!--added on API 17 (JBMR1 - 4.2)-->
<!--+++++++++++++++++++++++++++++-->
<string name="fontFamily__roboto_thin">sans-serif-thin</string>
<!--+++++++++++++++++++++++++++-->
<!--added on Lollipop (LL- 5.0)-->
<!--+++++++++++++++++++++++++++-->
<string name="fontFamily__roboto_medium">sans-serif-medium</string>
<string name="fontFamily__roboto_black">sans-serif-black</string>
<string name="fontFamily__roboto_condensed_light">sans-serif-condensed-light</string>
Android Studio 3.5+를 사용하는 경우 글꼴 변경이 매우 간단합니다.설계 보기에서 텍스트 위젯을 선택하고 속성 창에서 글꼴 패밀리를 확인합니다.값 드롭다운에는 하나를 선택할 수 있는 사용 가능한 모든 글꼴이 포함됩니다.Google 글꼴을 찾는 경우 추가 글꼴 옵션을 클릭합니다.
동적으로 이것을 사용하여 xml의 rodroid: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에 있습니다. 이 기본 글꼴 계열의 기본 글꼴에 대해 자세히 참조할 수 있습니다.
아래와 같이 res 디렉토리 아래에 글꼴 폴더를 추가하여 이 작업을 수행할 수도 있습니다.
https://www.1001fonts.com/, 에서 사용 가능한 글꼴을 찾은 다음 TTF 파일을 이 글꼴 디렉터리로 추출할 수 있습니다.
마지막으로, 안드로이드:fontFamily:"@font/urfontfilename"을 추가하여 텍스트 보기가 포함된 XML 파일을 변경하기만 하면 됩니다.
시행착오를 겪으면서 저는 다음과 같은 것을 배웠습니다.
*.xml 내에서 글꼴 글꼴을 글꼴뿐만 아니라 다음 기능과 결합할 수 있습니다.
android:fontFamily="serif"
android:textStyle="italic"
이 두 가지 스타일을 사용하면 다른 경우에 서체를 사용할 필요가 없습니다.글꼴 패밀리 &textStyle에서는 조합 범위가 훨씬 더 큽니다.
사용해 보십시오.
TextView textview = (TextView) findViewById(R.id.textview);
Typeface tf= Typeface.createFromAsset(getAssets(),"fonts/Tahoma.ttf");
textview .setTypeface(tf);
Android:fontFamily의 유효한 값은 /system/etc/system_fonts.xml(4.x) 또는 /system/etc/fonts.xml(5.x)에 정의되어 있습니다.그러나 장치 제조업체에서 수정할 수 있으므로 fontFamily 값을 설정하여 사용하는 실제 글꼴은 지정된 장치의 위에서 언급한 파일에 따라 달라집니다.
AOSP에서 Arial 글꼴은 유효하지만 Android:fontFamily="Arial"이 아닌 "Arial"을 사용하여 정의해야 합니다.Kitkat의 system_fonts.xml을 간단히 살펴봅니다.
<family>
<nameset>
<name>sans-serif</name>
<name>arial</name>
<name>helvetica</name>
<name>tahoma</name>
<name>verdana</name>
</nameset>
<fileset>
<file>Roboto-Regular.ttf</file>
<file>Roboto-Bold.ttf</file>
<file>Roboto-Italic.ttf</file>
<file>Roboto-BoldItalic.ttf</file>
</fileset>
</family>
//////////////////////////////////////////////////////////////////////////
레이아웃에서 "font"를 정의하기 위한 세 가지 관련 xml 속성이 있습니다. Android:fontFamily, Android:typeface 및 Android:textStyle."fontFamily"와 "textStyle" 또는 "typeface"와 "textStyle"의 조합을 사용하여 텍스트의 글꼴 모양을 변경할 수 있습니다.TextView.java의 코드 조각은 다음과 같습니다.
private void setTypefaceFromAttrs(String familyName, int typefaceIndex, int styleIndex) {
Typeface tf = null;
if (familyName != null) {
tf = Typeface.create(familyName, styleIndex);
if (tf != null) {
setTypeface(tf);
return;
}
}
switch (typefaceIndex) {
case SANS:
tf = Typeface.SANS_SERIF;
break;
case SERIF:
tf = Typeface.SERIF;
break;
case MONOSPACE:
tf = Typeface.MONOSPACE;
break;
}
setTypeface(tf, styleIndex);
}
public void setTypeface(Typeface tf, int style) {
if (style > 0) {
if (tf == null) {
tf = Typeface.defaultFromStyle(style);
} else {
tf = Typeface.create(tf, style);
}
setTypeface(tf);
// now compute what (if any) algorithmic styling is needed
int typefaceStyle = tf != null ? tf.getStyle() : 0;
int need = style & ~typefaceStyle;
mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0);
mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0);
} else {
mTextPaint.setFakeBoldText(false);
mTextPaint.setTextSkewX(0);
setTypeface(tf);
}
}
코드에서 확인할 수 있는 내용:
- "font Family"가 설정되어 있으면 "typeface"가 무시됩니다.
- "typeface"에 표준 및 제한된 유효 값이 있습니다.실제로 "일반" "sans" "serif" 및 "monospace" 값은 system_fonts.xml(4.x) 또는 fonts.xml(5.x)에서 찾을 수 있습니다.실제로 "일반"과 "산" 모두 시스템의 기본 글꼴입니다.
- "font 제품군"은 내장 글꼴의 모든 글꼴을 설정하는 데 사용할 수 있는 반면, "typeface"는 "sans-serif"와 "monospace"(세계 글꼴 유형의 세 가지 주요 범주)의 일반적인 글꼴만 제공합니다.
- "textStyle"만 설정하면 실제로 기본 글꼴과 지정된 스타일을 설정합니다.유효 값은 "일반" "굵은" "이탤릭체" 및 "굵은 |이탤릭체"입니다.
프로그램별로 글꼴을 설정하려면...
TextView tv7 = new TextView(this);
tv7.setText(" TIME ");
tv7.setTypeface(Typeface.create("sans-serif-condensed",Typeface.BOLD));
tv7.setTextSize(12);
tbrow.addView(tv7);
"sans-serif-condensed"라는 이름은 -app--> res--> values 폴더에 생성되어야 하는 fonts.xml 파일에서 참조되며 이 폴더에는 글꼴이 들어 있습니다.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="font_family_light">sans-serif-light</string>
<string name="font_family_medium">sans-serif-medium</string>
<string name="font_family_regular">sans-serif</string>
<string name="font_family_condensed">sans-serif-condensed</string>
<string name="font_family_black">sans-serif-black</string>
<string name="font_family_thin">sans-serif-thin</string>
</resources>
이것이 확실하기를 바랍니다!
경우에 따라 작동할 수 있는 더 쉬운 방법이 있습니다.원칙은 xml 레이아웃에 보이지 않는 TextV 뷰를 추가하고 Java 코드에서 해당 typeFace를 가져오는 것입니다.
xml 파일의 레이아웃:
<TextView
android:text="The classic bread is made of flour hot and salty. The classic bread is made of flour hot and salty. The classic bread is made of flour hot and salty."
android:layout_width="0dp"
android:layout_height="0dp"
android:fontFamily="sans-serif-thin"
android:id="@+id/textViewDescription"/>
그리고 자바 코드:
myText.setTypeface(textViewSelectedDescription.getTypeface());
(예를 들어 TextSwitcher 내에서) 작동했습니다.
<string name="font_family_display_4_material">sans-serif-light</string>
<string name="font_family_display_3_material">sans-serif</string>
<string name="font_family_display_2_material">sans-serif</string>
<string name="font_family_display_1_material">sans-serif</string>
<string name="font_family_headline_material">sans-serif</string>
<string name="font_family_title_material">sans-serif-medium</string>
<string name="font_family_subhead_material">sans-serif</string>
<string name="font_family_menu_material">sans-serif</string>
<string name="font_family_body_2_material">sans-serif-medium</string>
<string name="font_family_body_1_material">sans-serif</string>
<string name="font_family_caption_material">sans-serif</string>
<string name="font_family_button_material">sans-serif-medium</string>
다음과 같은 사용자 정의 글꼴 패밀리를 정의할 수 있습니다.
/res/font/usual.xml
:
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:ignore="UnusedAttribute">
<font
android:fontStyle="normal"
android:fontWeight="200"
android:font="@font/usual_regular"
app:fontStyle="normal"
app:fontWeight="200"
app:font="@font/usual_regular" />
<font
android:fontStyle="italic"
android:fontWeight="200"
android:font="@font/usual_regular_italic"
app:fontStyle="italic"
app:fontWeight="200"
app:font="@font/usual_regular_italic" />
<font
android:fontStyle="normal"
android:fontWeight="600"
android:font="@font/usual_bold"
app:fontStyle="normal"
app:fontWeight="600"
app:font="@font/usual_bold" />
<font
android:fontStyle="italic"
android:fontWeight="600"
android:font="@font/usual_bold_italic"
app:fontStyle="italic"
app:fontWeight="600"
app:font="@font/usual_bold_italic" />
</font-family>
이제 할 수 있습니다.
android:fontFamily="@font/usual"
당신의 다른 하나를 가정하면font
소문자와 함께 리소스도 있습니다._
s의
동일한 글꼴 패밀리를 가진 많은 장소에서 TextView를 사용하려면 TextView 클래스를 확장하고 다음과 같이 글꼴을 설정합니다.
public class ProximaNovaTextView extends TextView {
public ProximaNovaTextView(Context context) {
super(context);
applyCustomFont(context);
}
public ProximaNovaTextView(Context context, AttributeSet attrs) {
super(context, attrs);
applyCustomFont(context);
}
public ProximaNovaTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
applyCustomFont(context);
}
private void applyCustomFont(Context context) {
Typeface customFont = FontCache.getTypeface("proximanova_regular.otf", context);
setTypeface(customFont);
}
}
그런 다음 TextView에 대해 XML의 이 사용자 정의 클래스를 다음과 같이 사용합니다.
<com.myapp.customview.ProximaNovaTextView
android:id="@+id/feed_list_item_name_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14sp"
/>
안드로이드 내부의 글꼴에 대한 지옥이 끝나가고 있다는 것을 언급하고 싶습니다. 왜냐하면 올해 구글 IO에서 우리는 마침내 이것을 얻었기 때문입니다. -> https://developer.android.com/preview/features/working-with-fonts.html
이제 새로운 리소스 유형의 글꼴이 있으며 문자열 재설정 값, 그리기 가능한 재설정 값 등에 액세스할 수 있는 것처럼 모든 응용 프로그램 글꼴을 res/sys 폴더 안에 배치하고 R.font.my _custom_sys를 사용하여 액세스할 수 있습니다.사용자 정의 글꼴(이탤릭체, 굵게 표시 및 밑줄 표시)로 구성된 글꼴 얼굴 xml 파일을 만들 수도 있습니다.
자세한 내용은 위의 링크를 참조하십시오.응원법을 한번 볼까요.
또한 표준 글꼴을 변경할 수 있습니다.setTextAppearance
(API 16 참조), https://stackoverflow.com/a/36301508/2914140 :
<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){
TextViewCompat.setTextAppearance(textView, R.style.styleA);
} else {
TextViewCompat.setTextAppearance(textView,R.style.styleB);
}
새 글꼴 리소스에서 직접 설정할 수 있습니다.font
사용.
android:fontFamily="@font/my_font_in_font_folder"
Android-Studio 3 이상의 경우 이 스타일을 사용한 다음 모두를 사용할 수 있습니다.textView
앱에서 글꼴 변경.
이 스타일을 만듭니다.style.xml
:
<!--OverRide all textView font-->
<style name="defaultTextViewStyle" parent="android:Widget.TextView">
<item name="android:fontFamily">@font/your_custom_font</item>
</style>
그런 다음 테마에 사용합니다.
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:textViewStyle">@style/defaultTextViewStyle</item>
</style>
언급URL : https://stackoverflow.com/questions/12128331/how-to-change-fontfamily-of-textview-in-android
'programing' 카테고리의 다른 글
VBA에서 양식이 닫힐 때 코드 실행(Excel 2007) (0) | 2023.06.11 |
---|---|
iPhone에서 프로그래밍 방식으로 메모리 사용량 검색 (0) | 2023.06.01 |
루비의 문자열 연결 (0) | 2023.06.01 |
레일 모델, 뷰, 컨트롤러 및 도우미: 무엇이 가능합니까? (0) | 2023.06.01 |
UI 테이블 보기를 길게 누릅니다. (0) | 2023.06.01 |