2017-04-17 78 views
-1

我创建了一个android studio的默认导航视图,并且我在nav_header_main.xml中放置了两个按钮(请参见下图) 现在我想为按钮设置一个自定义字体。 我想这在MainActivity.java:设置导航视图标题的自定义字体

Typeface font = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf"); 
    Button b = (Button) findViewById(R.id.login_btn); 
    b.setTypeface(font); 

,但它没有工作! 我该怎么做?

Screenshot

+0

创建自定义类扩展Button类,然后用它来处理XML创建按钮,而不是默认

+0

看这个答案http://stackoverflow.com/a/16648457/7267105 –

+0

请准确解释“它没有工作”。 –

回答

0

你必须写从按钮延伸的自定义类。

下面是一个例子:

package com.example.test; 

import android.content.Context; 
import android.graphics.Typeface; 
import android.util.AttributeSet; 
import android.widget.Button; 
import android.widget.TextView; 

public class CustomFontButton extends Button { 

    public CustomFontButton(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     init(); 
    } 

    public CustomFontButton(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     init(); 
    } 

    public CustomFontButton(Context context) { 
     super(context); 
     init(); 
    } 

    private void init() { 
     Typeface font = Typeface.createFromAsset(getContext().getAssets(), "fonts/myfont.ttf"); 
     setTypeface(font); 
    } 

} 

从XML使用它:

<com.example.test.CustomFontButton 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Button Text" />