android style.xml出错,Android:如何在styles.xml中自定义声明XML命名空间?

博客介绍了在Android中自定义TextView字体样式的实现步骤。首先要在attr.xml文件中定义字体属性,接着为TextView定义自定义样式,还给出了布局代码和自定义TextView的代码示例,同时假设了字体资产的存放位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1)您需要在res文件夹的attr.xml文件中为字体定义一个属性:

2)您需要为TextView定义自定义样式,这里我们使用我们定义的属性(myfonts):

3)

ReallyCoolFont.ttf

总结你目前为止有什么

ReallyCoolFont.ttf

4)现在你的布局将是:

xmlns:app="http://schemas.android.com/apk/res-auto"

android:layout_width="match_parent"

android:layout_height="match_parent" >

android:id="@+id/result"

style="@style/CoolTextView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerInParent="true"

android:text="HELLO WORLD!"

android:textSize="24dp"

android:gravity="center" >

5)和你的MyCustomTextView是:

public class MyCustomTextView extends TextView {

private static final String TAG = "TextView";

public MyCustomTextView(Context context) {

super(context);

}

public MyCustomTextView(Context context, AttributeSet attrs) {

super(context, attrs);

settingFont(context, attrs);

}

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

super(context, attrs, defStyle);

settingFont(context, attrs);

}

private void settingFont(Context ctx, AttributeSet attrs) {

TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.MyCustomStyle);

String customFont = a.getString(R.styleable.MyCustomStyle_myfonts);

Typeface tf = null;

try {

tf = Typeface.createFromAsset(ctx.getAssets(), customFont);

} catch (Exception e) {

Log.e(TAG,e.getMessage());

a.recycle();

return;

}

setTypeface(tf);

a.recycle();

}

}

我假设你把字体的资产不在asset / fonts目录中.

还强烈推荐阅读this.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值