Android 在运行时设置字体,Textview
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3483110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
set font at runtime, Textview
提问by Shishir.bobby
How to set font to textview, which is created at runtime?
如何将字体设置为在运行时创建的 textview?
i created textview
我创建了文本视图
Textview tv = new TextView(this);
tv.setTextSize(20);
like I can change the size
i want to set font style to "Verdana".
就像我可以更改大小,
我想将字体样式设置为“Verdana”。
How to do this?? regards shishir
这该怎么做??问候 shishir
回答by Paresh Mayani
To set In-built Font at Run-Time:
在运行时设置内置字体:
First of all, To Change Font-face, a Typefaceclass is used.
Now,
at Run-Time
, to set the font-face, UsesetTypeface(Typeface)
from the Java codeat Design-Time
, to set the font-face, Useandroid:typeface="serif"
首先,要更改字体,使用字体类。
现在,
at Run-Time
要设置字体,请setTypeface(Typeface)
从 Java 代码中使用at Design-Time
, 设置字体,使用android:typeface="serif"
For example:
例如:
<TextView android:text="@+id/TextView01"
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30px"
android:textStyle="italic"
android:typeface="serif" />
To set Custom font(s) in your Android application
在 Android 应用程序中设置自定义字体
To do this, simply create an assets/ folder in the project root, and put your fonts (in TrueType, or TTF, form) in the assets. You might, for example, create assets/fonts/
and put your TTF files in there:
为此,只需在项目根目录中创建一个 assets/ 文件夹,并将您的字体(以 TrueType 或 TTF 形式)放入资产中。例如,assets/fonts/
您可以在其中创建并放置 TTF 文件:
TextView tv=(TextView)findViewById(R.id.custom);
Typeface face=Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf");
tv.setTypeface(face);
回答by Dilroop Singh
You can have .ttf font in your asset folder. Say font's name is "default.ttf" and you just now have to write below 2 lines of code
您可以在资产文件夹中使用 .ttf 字体。假设字体的名称是“default.ttf”,您现在必须编写以下 2 行代码
TextView text = new TextView(this);
text.setTypeface(Typeface.createFromAsset(getAssets(), "default.ttf"));
You must also we careful because different font have different sizes. You may need to set size as :
你也必须小心,因为不同的字体有不同的大小。您可能需要将大小设置为:
text.setTextSize(20);
回答by Rahul Sharma
With introduction of Fonts in XMLin Android 8.0 (backward compatible from API version 14) its very easy to set font from xml itself.
随着Android 8.0中 XML 字体的引入(从 API 版本 14 向后兼容),从 xml 本身设置字体非常容易。
From the android documentation:
从安卓文档:
Android 8.0 (API level 26) introduces a new feature, Fonts in XML, which lets you use fonts as resources. You can add the font file in the res/font/ folder to bundle fonts as resources. These fonts are compiled in your R file and are automatically available in Android Studio. You can access the font resources with the help of a new resource type, font. For example, to access a font resource, use @font/myfont, or R.font.myfont.
Android 8.0(API 级别 26)引入了一项新功能,XML 中的字体,可让您将字体用作资源。您可以在 res/font/ 文件夹中添加字体文件,将字体捆绑为资源。这些字体在您的 R 文件中编译,并在 Android Studio 中自动可用。您可以在新资源类型 font 的帮助下访问字体资源。例如,要访问字体资源,请使用 @font/myfont 或 R.font.myfont。
Firstly create a Android Resource Directoryin res
folder named as font
Add your .ttf font file to that directory, and then create font family
首先在名为font 的文件夹中创建一个Android Resource Directory将您的 .ttf 字体文件添加到该目录中,然后创建字体系列res
Create a font family
创建字体系列
A font family is a set of font files along with its style and weight details. In Android, you can create a new font family as an XML resource and access it as a single unit, instead of referencing each style and weight as separate resources. By doing this, the system can select the correct font based on the text style you are trying to use.
字体系列是一组字体文件及其样式和粗细详细信息。在 Android 中,您可以创建一个新的字体系列作为 XML 资源并将其作为一个单元访问,而不是将每个样式和粗细作为单独的资源进行引用。通过这样做,系统可以根据您尝试使用的文本样式选择正确的字体。
To create a font family, perform the following steps in the Android Studio:
要创建字体系列,请在 Android Studio 中执行以下步骤:
- Right-click the font folder and go to New > Font resource file. The New Resource File window appears.
- Enter the file name, and then click OK. The new font resource XML opens in the editor.
Enclose each font file, style, and weight attribute in the
<font>
element. The following XML illustrates adding font-related attributes in the font resource XML:<?xml version="1.0" encoding="utf-8"?> <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>
- 右键单击字体文件夹,然后转到新建 > 字体资源文件。出现“新建资源文件”窗口。
- 输入文件名,然后单击“确定”。新字体资源 XML 在编辑器中打开。
在
<font>
元素中包含每个字体文件、样式和粗细属性。以下 XML 说明在字体资源 XML 中添加与字体相关的属性:<?xml version="1.0" encoding="utf-8"?> <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>
Then use the following code to set font in your textView
like
然后使用以下代码设置您textView
喜欢的字体
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/lobster"/>
回答by anand krish
Dynamically you can set the fontfamily similar to android:fontFamily in xml by using this,
你可以使用这个动态设置类似于 android:fontFamily 在 xml 中的字体家族,
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));
These are the list of default fontfamily used, use any of this by replacing the double quotation string "sans-serif-medium"
这些是使用的默认字体系列的列表,通过替换双引号字符串“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" is the ttf file. Pathwill be in src/assets/fonts/mycustomfont.ttf
“mycustomfont.ttf”是 ttf 文件。路径将在src/assets/fonts/mycustomfont.ttf
回答by Joseph Earl
Here is a small utility class
这是一个小的实用程序类
public class TypefaceHelper {
public static void setViewGroupTypeface(ViewGroup container, Typeface typeface) {
final int children = container.getChildCount();
for (int i = 0; i < children; i++)
View child = container.getChildAt(i);
if (child instanceof TextView) {
setTextViewTypeface((TextView) child, typeface);
} else if (child instanceof ViewGroup) {
setViewGroupTypeface((ViewGroup) child, typeface);
}
}
}
public static void setTextViewTypeface(TextView textView, Typeface typeface) {
textView.setTypeface(typeface);
}
}
For things like Spinner
s or ListView
s (i.e. any kind of AdapterView
) which generate their children from an adapter you will need to set the typeface of each item View
in the getView
(or similar) method of the adapter. This is because views may be created as needed and so setting the Typeface
in onCreate
won't work properly.
对于像Spinner
s 或ListView
s (即任何类型的AdapterView
)从适配器生成其子项的事情,您需要在适配器View
的getView
(或类似)方法中设置每个项目的字体。这是因为可能会根据需要创建视图,因此设置Typeface
inonCreate
将无法正常工作。
回答by mmmcho
If you don't want to use typeface and fiddle around with the path to your font file (Which may crash your application if you put in an incorrect path), here's another way.
如果您不想使用字体并随意修改字体文件的路径(如果您输入的路径不正确,可能会使您的应用程序崩溃),这是另一种方法。
First create a style in your styles.xml
首先在您的样式中创建样式 styles.xml
<style name="YourFont">
<item name="android:fontFamily">@font/your_font</item>
</style>
Then you can just add the style using
然后你可以使用添加样式
textView.setTextAppearance(context, R.style.YourFont);
回答by mihir ahir
you can use your font which you have store in font "res/font" ex. for API level 16 and above.
您可以使用您存储在字体“res/font”中的字体,例如。API 级别 16 及以上。
Typeface typeface = ResourcesCompat.getFont(context, R.font.rubik_medium);
txtView.setTypeface(typeface);
you can also use
你也可以使用
Typeface typeface = getResources().getFont(R.font.rubik_medium);
txtView.setTypeface(typeface);
but it support with API level 26 and above.
但它支持 API 级别 26 及以上。
回答by Asahi
You need to use Typeface:
您需要使用字体:
- add font you wish to use to your project as asset.
create Typeface object using that font:
Typeface myFont = Typeface.createFromAsset(getAssets(), "fonts/MyFont.ttf");
set typeface to the object you'd like to customize:
TextView myTextView = (TextView)findViewById(R.id.my_text_view); myTextView.setTypeface(myFont);
- 将您希望使用的字体作为资产添加到您的项目中。
使用该字体创建 Typeface 对象:
Typeface myFont = Typeface.createFromAsset(getAssets(), "fonts/MyFont.ttf");
将字体设置为您要自定义的对象:
TextView myTextView = (TextView)findViewById(R.id.my_text_view); myTextView.setTypeface(myFont);
回答by Muzikant
You can use the following code to set all your text to a specific font at runtime. Just call the setViewGroupFont
method at the end of your Activity onCreate
method or whenever you dynamically create new views:
您可以使用以下代码在运行时将所有文本设置为特定字体。只需setViewGroupFont
在 ActivityonCreate
方法结束时或在动态创建新视图时调用该方法:
private static final String FONT_NAME = "fonts/Roboto-Regular.ttf";
private static Typeface m_font = null;
public static Typeface getFont(Context p_context)
{
if (null == m_font && null != p_context)
{
m_font = Typeface.createFromAsset(p_context.getApplicationContext().getAssets(), FONT_NAME);
}
return m_font;
}
public static void setViewGroupFont(ViewGroup p_viewGroup)
{
if (null != p_viewGroup)
{
for (int currChildIndex = 0; currChildIndex < p_viewGroup.getChildCount(); currChildIndex++)
{
View currChildView = p_viewGroup.getChildAt(currChildIndex);
if (ViewGroup.class.isInstance(currChildView))
{
setViewGroupFont((ViewGroup) currChildView);
}
else
{
try
{
Method setTypefaceMethod = currChildView.getClass().getMethod("setTypeface", Typeface.class);
setTypefaceMethod.invoke(currChildView, getFont(p_viewGroup.getContext()));
}
catch (NoSuchMethodException ex)
{
// Do nothing
}
catch (Exception ex)
{
// Unexpected error setting font
}
}
}
}
}