2012-03-15 163 views
1

對於我一直在開發的Android小部件,我嘗試使用自定義字體。我在網上查了一些教程,並找到了幾種方法來做到這一點。我選擇了一個並試圖實現它,但是我得到一個錯誤,我無法弄清楚爲什麼。該技術使用一個獨立的類(我已經發布了下面的代碼)來設置字體。在這段代碼中,我在setCustomFont中的customFont行發生錯誤。它表示customFont不能解析爲變量。有誰能幫我解釋爲什麼會發生這種情況嗎?設置自定義字體錯誤 - Android

import android.content.Context; 
import android.content.res.TypedArray; 
import android.graphics.Typeface; 
import android.util.AttributeSet; 
import android.util.Log; 
import android.widget.TextView; 

public class TypefacedTextView extends TextView { 
private static final String TAG = "TextView"; 

public TypefacedTextView(Context context) { 
    super(context); 
} 

public TypefacedTextView(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    setCustomFont(context, attrs); 
} 

public TypefacedTextView(Context context, AttributeSet attrs, int defStyle) { 
    super(context, attrs, defStyle); 
    setCustomFont(context, attrs); 
} 

private void setCustomFont(Context ctx, AttributeSet attrs) { 
    TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TypefacedTextView); 
    String customFontl = a.getString(R.styleable.TypefacedTextView_typeface); 
    setCustomFont(ctx, customFont); //      get an error here 
    a.recycle(); 
} 

public boolean setCustomFont(Context ctx, String asset) { 
    Typeface tf = null; 
    try { 
    tf = Typeface.createFromAsset(ctx.getAssets(), asset); 
    } catch (Exception e) { 
     Log.e(TAG, "Could not get typeface: " + e.getMessage()); 
     return false; 
    } 

    setTypeface(tf); 
    return true; 
} 

}

+1

請分享日誌。 – Abhinava 2012-03-15 07:28:17

回答

0
String customFontl = a.getString(R.styleable.TypefacedTextView_typeface); 
setCustomFont(ctx, customFont); //      get an error here 

您的變量聲明爲customFontl(注意最後l),你要使用它作爲customFont。我猜想錯誤是customFont沒有定義或類似的情況,因爲它是這樣的。

+0

好吧,這只是一個錯字,感謝您注意到這一點;)。我的代碼據說很好(根據日食),但是當我啓動我的小部件時,它告訴我它不能顯示。此錯誤必須位於自定義字體部分,因爲在嘗試使用自定義字體之前它工作正常 – Zero 2012-03-15 08:47:12

0

我有嘗試,這可能是幫助你在這段代碼我的字體是在資產/ fonts文件夾 如果只是在asseet比代碼的字體替換/

public class MyTextView extends TextView{ 

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

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

    public MyTextView(Context context) { 
     super(context); 
     init(); 
     rotate(); 
    } 

    private void rotate() { 
     // TODO Auto-generated method stub 
     setSelected(true); 
    } 

    private void init() { 
     if (!isInEditMode()) { 
      Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/TrajanPro-Regular.otf"); 
      setTypeface(tf); 
     } 
    } 


}