2017-08-31 25 views
-6

下面的代碼是使用trebuchet字體的自定義textview類。當我在android studio中使用自定義textview時發生錯誤

public class TrebuchetTextView extends TextView { 

    public TrebuchetTextView(Context context) { 
     super(context); 

     init(); 
    } 

    public TrebuchetTextView(Context context, AttributeSet attrs) { 
     super(context, attrs); 

     init(); 
    } 

    public TrebuchetTextView(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 

     init(); 
    } 

    private void init() { 
     if (!isInEditMode()) { 
      final Typeface typeface = Typeface.createFromAsset(getContext().getAssets(), getContext().getString(R.string.normal_font_path)); 
     setTypeface(typeface); 
     } 
    } 
} 

這是用於其他應用程序,並運作良好。

但是,當我在我的應用程序中使用自定義textview時會發生通貨膨脹錯誤。 我在資產/字體文件夾中包含trebuchet字體。

+3

份額問題 –

+0

如果你只是想改變應用程序的所有的TextView的的字體,你可以用另一種方法的錯誤。 – Khan

+0

在xml文件中使用自定義textview及其完整軟件包路徑。此外,這必須是'getContext()。getResources()。getString(R.string.normal_font_path)' – Piyush

回答

0

試試這個下面的代碼定製textview

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

public class FontTextView extends TextView { 


    public FontTextView(Context context) { 
     super(context); 
     Typeface face=Typeface.createFromAsset(context.getAssets(), "Helvetica_Neue.ttf"); 
     this.setTypeface(face); 
    } 

    public FontTextView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    Typeface face=Typeface.createFromAsset(context.getAssets(), "Helvetica_Neue.ttf"); 
    this.setTypeface(face); 
    } 

    public FontTextView(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
    Typeface face=Typeface.createFromAsset(context.getAssets(), "Helvetica_Neue.ttf"); 
    this.setTypeface(face); 
    } 

    protected void onDraw (Canvas canvas) { 
     super.onDraw(canvas); 


    } 

} 

和XML:

<com.util.FontTextView 
        android:id="@+id/textView2" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="@string/accountInfoText" 
        android:textColor="#727272" 
        android:textSize="18dp" /> 
+0

它不起作用。發生同樣的錯誤。 –

+0

您面臨的錯誤 –

+0

原因是字體錯位。抱歉... –

0

試試這個自定義textview其全包路徑在layout.xml文件中像這樣

<com.example.pkg.TextView 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" /> 

並改變這條線在你customtextview

Typeface face=Typeface.createFromAsset(context.getAssets(), "yourfont.ttf"); 
+0

我確實已經.. –

+0

原因是字體錯位。對不起... –

+0

@권준동不客氣。不要忘記註冊並標記答案 –

相關問題