使用このカスタムフォントクラス
public class TextView extends android.widget.TextView {
Context mContext;
String str;
//fonts
public static Typeface Font_name;
public TextView(Context context) {
super(context);
mContext=context;
initialiseFont(null);
}
public TextView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext=context;
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TextView, 0, 0);
try {
str = ta.getString(R.styleable.TextView_font_family);
} finally {
ta.recycle();
}
initialiseFont(str);
}
public TextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext=context;
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TextView, 0, 0);
try {
str = ta.getString(R.styleable.TextView_font_family);
} finally {
ta.recycle();
}
initialiseFont(str);
}
public TextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
mContext=context;
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TextView, 0, 0);
try {
str = ta.getString(R.styleable.TextView_font_family);
} finally {
ta.recycle();
}
initialiseFont(str);
}
private void initialiseFont(String font) {
if(font==null || font.equals("")){
}
else {
Font_name = Typeface.createFromAsset(mContext.getAssets(), font);
setTypeface(Font_name);
}
}
}
はarrs.xmlにこのタグを追加しますカスタム属性font-familyを読み取る
あなたがのTextViewを使用している場合
<resources>
<declare-styleable name="TextView">
<attr name="font_family" format="string"/>
</declare-styleable>
</resources>
は、すべての活動に新たな書体のインスタンスを作成すると間違って何どこでも
<Your_package_name_which_you_created_custom_font_class.TextView
android:text="Hello World!"
android:layout_width="wrap_content"
app:font_family="OpenSans-Bold.ttf"
android:layout_height="wrap_content" />
資産フォルダ(使用同じファイル名)にフォントをコピーし、このタグを使用しますか?または、書体を作成する静的なファクトリメソッドですか?あなたがしようとしていることは技術的に可能ですが、メモリリークを作成するために役立つだけで、あなたが知っていることが悪いことであると思います。 –
@XaverKapellerさまざまなアクティビティで書体を使用したいと思っていましたが、重複すると思いましたので、ヘルパークラスを作成することにしました。どのようにしてメモリリークが発生するのですか?私はちょうどそれが私が探していたことをしている最後の例で[この投稿](http://martin.cubeactive.com/android-how-to-use-a-custom-font/)を読んで、これはまだメモリリークを作成する? –
はい、インターネット上のランダムなブログ投稿を盲目的に追跡してはいけません。ヘルパークラスを持つことは悪いことではありませんが、この投稿のヘルパークラスの実装は、書体が作成されたコンテキストをリークするため問題になります。この単純な問題を解決する方法は、タイプフェイスへの参照を保持する静的変数を持たないことです。代わりに、コンテキストをヘルパーメソッドに渡して、各アクティビティの新しいTypefaceインスタンスを作成します。 –