SOで提示されたすべてのソリューションに満足できなかったので、私は自分のものを思いつきました。これは、タグを使ったちょっとしたトリック (つまり、コード内でタグを使用できない) に基づいており、そこにフォント パスを配置しました。したがって、ビューを定義するときは、次のいずれかを実行できます。
<TextView
android:id="@+id/textViewHello1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World 1"
android:tag="fonts/Oswald-Regular.ttf"/>
またはこれ:
<TextView
android:id="@+id/textViewHello2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World 2"
style="@style/OswaldTextAppearance"/>
<style name="OswaldTextAppearance">
<item name="android:tag">fonts/Oswald-Regular.ttf</item>
<item name="android:textColor">#000000</item>
</style>
これで、次のようにビューに明示的にアクセス/セットアップできます。
TextView textView = TextViewHelper.setupTextView(this, R.id.textViewHello1).setText("blah");
または、次の方法ですべてをセットアップします。
TextViewHelper.setupTextViews(this, (ViewGroup) findViewById(R.id.parentLayout)); // parentLayout is the root view group (relative layout in my case)
そして、あなたが尋ねる魔法のクラスは何ですか?アクティビティとフラグメントの両方のヘルパー メソッドを使用して、ほとんど別の SO 投稿から接着されています。
import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.HashMap;
import java.util.Map;
public class TextViewHelper {
private static final Map<String, Typeface> mFontCache = new HashMap<>();
private static Typeface getTypeface(Context context, String fontPath) {
Typeface typeface;
if (mFontCache.containsKey(fontPath)) {
typeface = mFontCache.get(fontPath);
} else {
typeface = Typeface.createFromAsset(context.getAssets(), fontPath);
mFontCache.put(fontPath, typeface);
}
return typeface;
}
public static void setupTextViews(Context context, ViewGroup parent) {
for (int i = parent.getChildCount() - 1; i >= 0; i--) {
final View child = parent.getChildAt(i);
if (child instanceof ViewGroup) {
setupTextViews(context, (ViewGroup) child);
} else {
if (child != null) {
TextViewHelper.setupTextView(context, child);
}
}
}
}
public static void setupTextView(Context context, View view) {
if (view instanceof TextView) {
if (view.getTag() != null) // also inherited from TextView's style
{
TextView textView = (TextView) view;
String fontPath = (String) textView.getTag();
Typeface typeface = getTypeface(context, fontPath);
if (typeface != null) {
textView.setTypeface(typeface);
}
}
}
}
public static TextView setupTextView(View rootView, int id) {
TextView textView = (TextView) rootView.findViewById(id);
setupTextView(rootView.getContext().getApplicationContext(), textView);
return textView;
}
public static TextView setupTextView(Activity activity, int id) {
TextView textView = (TextView) activity.findViewById(id);
setupTextView(activity.getApplicationContext(), textView);
return textView;
}
}