[英]Setting TextView to bold font with xml-attribute and custom font (not working)
[英]Custom Textview Font not working
我想在textview上使用其他字体。 我已经创建了自定义textview类并创建了fonts文件夹。问题是编译后字体没有更改。我不知道我犯了什么错误。希望你们能帮助我解决这个问题。在此先感谢您
activity_example_one.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.khoi.androidexample.example.Example_One_Activity">
<com.khoi.androidexample.custom.TextViewBold
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/texview_bold_id"
android:text="Hello World!"/>
<com.khoi.androidexample.custom.TextViewMedium
android:layout_width="match_parent"
android:id="@+id/textview_medium_id"
android:layout_height="wrap_content"
android:text="Hello World!"/>
</LinearLayout>
Example_One_Activity.java
public class Example_One_Activity extends AppCompatActivity {
TextViewBold textViewBold;
TextViewMedium textViewMedium;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example_one);
textViewBold = (TextViewBold) findViewById(R.id.texview_bold_id);
textViewMedium = (TextViewMedium) findViewById(R.id.textview_medium_id);
}
}
TextViewBold.java
公共类TextViewBold扩展了TextView {
public TextViewBold(Context context, AttributeSet attrs, int defStyle){
super(context, attrs, defStyle);
init(context);
}
public TextViewBold(Context context,AttributeSet attrs){
super(context,attrs);
init(context);
}
public TextViewBold(Context context){
super(context);
init(context);
}
private void init(Context context) {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(context.getAssets(),"Lato_Medium.ttf");
setTypeface(tf);
}
}
}
您的地址中缺少“ fonts /”,应该是这样的:
setTypeface(Typeface.createFromAsset(getContext().getAssets(),"fonts/Lato_Medium.ttf"));
在您的init中传递上下文(Context上下文)
和getAssets()一样-> context.getAssets()
Typeface tf = Typeface.createFromAsset(context.getAssets(),"Lato_Medium.ttf");
isInEditMode()->确保它将返回true
我重新下载了字体样式并替换了fonts文件夹中的文件,它确实起作用。非常感谢您帮助解决了此问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.