In my application I am implementing 5 different Custom App Themes.
I am using 5 different fonts for these themes for which I have created CustomTextview which extends a Textview. Following is the format in which it is created.
public class CustomFontTextView extends TextView {
private static final String CUSTOM_FONT = "Custom-Regular.ttf";
private static final String TAG = CustomFontTextView.class.getName();
public CustomFontTextView(Context context) {
super(context);
if (android.os.Build.VERSION.SDK_INT < 14) {
setCustomFont(context, CUSTOM_FONT);
}
}
public CustomFontTextView(Context context, AttributeSet attrs) {
super(context, attrs);
if (android.os.Build.VERSION.SDK_INT < 14) {
setCustomFont(context, CUSTOM_FONT);
}
}
public CustomFontTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
if (android.os.Build.VERSION.SDK_INT < 14) {
setCustomFont(context, CUSTOM_FONT);
}
}
public boolean setCustomFont(Context ctx, String fontFile) {
try {
setTypeface(Typeface.createFromAsset(ctx.getAssets(), fontFile));
return true;
} catch (Exception e) {
Log.e(TAG, "Could not get typeface: "+e.getMessage());
return false;
}
}
}
I was using the custom textview in the XML layouts.
<com.myapp.android.fonts.CustomFontTextView
android:id="@+id/Text_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/my_text_content"
android:textColor="@android:color/white"
android:textSize="22sp" />
But for implementing the different themes I have to find some methods which would change all my textviews according to the themes selected.
Is there any way by which I can set the fonts within my theme,
<style name="MyCustomTheme" parent="android:style/Theme">
.............. ......................
........... ...................
<item name="android:textColorPrimary">#000000</item>
<item name="android:buttonStyle">@style/MyCustomButton</item>
</style>
I want to implement this without disturbing the code as there are a lot of UI components involved.
Create a custom attribute for the font and include it in the style. In your CustomView class, access this attribute and set the font accordingly.
Check Creating a View Class for more details.