android怎么改变按钮字体,Android帮助改变按钮字体类型,如何?

如果您打算将相同的字体添加到多个按钮,我建议您一直使用并将其实现为样式和子类按钮:

public class ButtonPlus extends Button {

public ButtonPlus(Context context) {

super(context);

}

public ButtonPlus(Context context, AttributeSet attrs) {

super(context, attrs);

CustomFontHelper.setCustomFont(this, context, attrs);

}

public ButtonPlus(Context context, AttributeSet attrs, int defStyle) {

super(context, attrs, defStyle);

CustomFontHelper.setCustomFont(this, context, attrs);

}

}

这是一个帮助类,用于在TextView上设置字体(记住,Button是TextView的子类),基于com.my.package:font属性:

public class CustomFontHelper {

/**

* Sets a font on a textview based on the custom com.my.package:font attribute

* If the custom font attribute isn't found in the attributes nothing happens

* @param textview

* @param context

* @param attrs

*/

public static void setCustomFont(TextView textview, Context context, AttributeSet attrs) {

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomFont);

String font = a.getString(R.styleable.CustomFont_font);

setCustomFont(textview, font, context);

a.recycle();

}

/**

* Sets a font on a textview

* @param textview

* @param font

* @param context

*/

public static void setCustomFont(TextView textview, String font, Context context) {

if(font == null) {

return;

}

Typeface tf = FontCache.get(font, context);

if(tf != null) {

textview.setTypeface(tf);

}

}

}

这是FontCache减少旧设备上的内存使用量:

public class FontCache {

private static Hashtable fontCache = new Hashtable();

public static Typeface get(String name, Context context) {

Typeface tf = fontCache.get(name);

if(tf == null) {

try {

tf = Typeface.createFromAsset(context.getAssets(), name);

}

catch (Exception e) {

return null;

}

fontCache.put(name, tf);

}

return tf;

}

}

在res / values / attrs.xml中,我们定义了自定义样式属性

最后在布局中使用示例:

style="@style/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/button_sometext"/>

在res / values / style.xml中

fonts/copperplate_gothic_light.TTF

这可能看起来像是一项非常多的工作,但是一旦你想要改变字体的几个按钮和文本字段,你会感谢我。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值