我试图在Android Studio中使用自定义字体,就像我们在Eclipse中所做的那样。但不幸的是,不知道在哪里放“资产”文件夹!
当前回答
如果你像我一样对Android非常陌生,这可能有点棘手。请务必致电:
TextView myTextView = (TextView) findViewById(R.id.textView);
Typeface typeface=Typeface.createFromAsset(getAssets(), "fonts/your font.ttf");
myTextView.setTypeface(typeface);
方法,例如onCreate。
其他回答
如果你像我一样对Android非常陌生,这可能有点棘手。请务必致电:
TextView myTextView = (TextView) findViewById(R.id.textView);
Typeface typeface=Typeface.createFromAsset(getAssets(), "fonts/your font.ttf");
myTextView.setTypeface(typeface);
方法,例如onCreate。
首先创建资产文件夹,然后在其中创建字体文件夹。
然后你可以设置字体从资产或目录如下:
public class FontSampler extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.custom);
Typeface face = Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf");
tv.setTypeface(face);
File font = new File(Environment.getExternalStorageDirectory(), "MgOpenCosmeticaBold.ttf");
if (font.exists()) {
tv = (TextView) findViewById(R.id.file);
face = Typeface.createFromFile(font);
tv.setTypeface(face);
} else {
findViewById(R.id.filerow).setVisibility(View.GONE);
}
}
}
使用支持库26.0(和Android O)字体可以轻松地从资源加载:
Typeface typeface = ResourcesCompat.getFont(Context context, int fontResourceId)
方法的文档。
更多信息可以在这里找到。
在项目中添加字体
添加字体作为资源,在Android Studio中执行以下步骤:
1 -右键单击res文件夹,进入New > Android资源目录。 出现“新建资源目录”窗口。
2 -在“资源类型”列表中,选择“字体”,单击“确定”。 3 -添加您的字体文件在字体文件夹只是一个简单的复制和粘贴。注意字体的名称应该是小写的。
使用XML布局中的字体
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/lobster"/>
向样式添加字体
<style name="customfontstyle" parent="@android:style/TextAppearance.Small">
<item name="android:fontFamily">@font/lobster</item>
</style>
以编程方式使用字体
科特林:
val typeface = resources.getFont(R.font.myfont)
textView.typeface = typeface
JAVA:
Typeface typeface = getResources().getFont(R.font.myfont);
textView.setTypeface(typeface);
首先在字体文件夹中添加font.ttf文件。然后在onCreate方法中添加这一行
Typeface typeface = ResourcesCompat.getFont(getApplicationContext(), R.font.myfont);
mytextView.setTypeface(typeface);
这是我的xml
<TextView
android:id="@+id/idtext1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="7dp"
android:gravity="center"
android:text="My Text"
android:textColor="#000"
android:textSize="10sp"
/>
推荐文章
- 如何允许所有网络连接类型HTTP和HTTPS在Android(9)馅饼?
- Android加载JS包失败
- Android Studio, logcat在应用程序关闭后清理
- 在android中从上下文获取活动
- 无法解析主机"<URL here>"没有与主机名关联的地址
- getActivity()在Fragment函数中返回null
- 按钮背景是透明的
- 在Mac OS X上哪里安装Android SDK ?
- 我如何获得图像缩放功能?
- 在Android应用程序中显示当前时间和日期
- BottomSheetDialogFragment的圆角
- 在应用程序启动时出现“无法获得BatchedBridge,请确保您的bundle被正确打包”的错误
- 我如何改变默认对话框按钮的文本颜色在安卓5
- 更改单选按钮的圆圈颜色
- 如何在android中复制一个文件?