簡體   English   中英

自定義Textview字體不起作用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM