代码之家  ›  专栏  ›  技术社区  ›  khoi

自定义文本视图字体不工作

  •  0
  • khoi  · 技术社区  · 7 年前

    我想在文本视图上使用其他字体。我已经创建了自定义textview类并创建了fonts文件夹。问题是编译后字体没有改变。我不知道我犯了什么错误。我希望你们能帮我解决这个问题。提前谢谢你

    enter image description here

    enter image description here

    activity\u example\u 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>
    

    示例\u One\u活动。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);
        }
    
    }
    

    文本视图粗体。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);
        }
    }
    

    }

    3 回复  |  直到 7 年前
        1
  •  1
  •   Ranjithkumar    7 年前

    在中传递上下文 初始化(上下文上下文)

    和getAssets()类似-->上下文getAssets()

    Typeface tf = Typeface.createFromAsset(context.getAssets(),"Lato_Medium.ttf");
    

    isInEditMode()-->确保返回true

        2
  •  1
  •   Mehdi bahmanpour    7 年前

    您的地址中缺少“字体/”,应该是这样的:

             setTypeface(Typeface.createFromAsset(getContext().getAssets(),"fonts/Lato_Medium.ttf"));
    
        3
  •  0
  •   khoi    7 年前

    我重新下载了字体样式并替换了fonts文件夹中的文件,它成功了。非常感谢您帮助解决此问题