2

在我的應用程序中,我正在實施5 different Custom App Themes根據android應用程序中的自定義主題在自定義文字瀏覽之間切換

我對這些主題使用了5種不同的字體,我創建了CustomTextview,它擴展了Textview。以下是它的創建格式。

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; 
    } 
} 

}

我使用的XML佈局定製的TextView。

<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" /> 

但是爲了實現不同的主題,我必須找到一些方法,這些方法會根據所選主題改變我的所有文字瀏覽。

有沒有什麼辦法讓我可以在我的主題中設置字體,

 <style name="MyCustomTheme" parent="android:style/Theme"> 
       .............. ...................... 
      ...........  ................... 
     <item name="android:textColorPrimary">#000000</item> 
     <item name="android:buttonStyle">@style/MyCustomButton</item> 
     </style> 

我想因爲有涉及大量的UI組件來實現這一點沒有干擾的代碼。

回答

1

爲字體創建自定義屬性並將其包含在樣式中。在您的CustomView類中,訪問此屬性並相應地設置字體。

檢查Creating a View Class瞭解更多詳情。

+0

嗨Rajesh,我將能夠通過創建** TextView **而不是XML佈局中的customTextview來實現此目的嗎?我想在不同的時間使用單一的XML佈局顯示5種不同的字體(_選擇不同的主題時)。我在佈局中使用的'com.myapp.android.fonts.CustomFontTextView'不允許我這樣做..! – DroidBee