根据Android应用程序中的自定义主题在自定义文本视图之间切换

时间:2012-12-11 07:10:11

标签: android android-layout textview android-ui android-theme

在我的应用程序中,我正在实施5 different Custom App Themes

我为这些主题使用了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 个答案:

答案 0 :(得分:1)

为字体创建自定义属性并将其包含在样式中。在CustomView类中,访问此属性并相应地设置字体。

查看Creating a View Class了解详情。