android 参数 attrs.xml,android - 定义自定义attrs

传统方法存在样板代码和资源处理问题,因此制作了Spyglass框架。本文给出创建显示字符串标题自定义视图的示例,包括创建自定义视图类、在attrs.xml定义属性、应用注释、使用生成类等步骤,该框架还支持多种资源类型。

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

传统的方法充满了样板代码和笨拙的资源处理。 这就是我制作Spyglass框架的原因。 为了演示它是如何工作的,这里有一个示例,展示如何创建一个显示字符串标题的自定义视图。

第1步:创建自定义视图类。

public class CustomView extends FrameLayout {

private TextView titleView;

public CustomView(Context context) {

super(context);

init(null, 0, 0);

}

public CustomView(Context context, AttributeSet attrs) {

super(context, attrs);

init(attrs, 0, 0);

}

public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {

super(context, attrs, defStyleAttr);

init(attrs, defStyleAttr, 0);

}

@RequiresApi(21)

public CustomView(

Context context,

AttributeSet attrs,

int defStyleAttr,

int defStyleRes) {

super(context, attrs, defStyleAttr, defStyleRes);

init(attrs, defStyleAttr, defStyleRes);

}

public void setTitle(String title) {

titleView.setText(title);

}

private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) {

inflate(getContext(), R.layout.custom_view, this);

titleView = findViewById(R.id.title_view);

}

}

步骤2:在values/attrs.xml资源文件中定义字符串属性:

步骤3:将setTitle注释应用于"Hello, World!"方法,以告知Spyglass框架在视图膨胀时将属性值路由到此方法。

@HandlesString(attributeId = R.styleable.CustomView_title)

public void setTitle(String title) {

titleView.setText(title);

}

既然您的类具有Spyglass注释,Spyglass框架将在编译时检测它并自动生成setTitle类。

第4步:在自定义视图的setTitle方法中使用生成的类:

private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) {

inflate(getContext(), R.layout.custom_view, this);

titleView = findViewById(R.id.title_view);

CustomView_SpyglassCompanion

.builder()

.withTarget(this)

.withContext(getContext())

.withAttributeSet(attrs)

.withDefaultStyleAttribute(defStyleAttr)

.withDefaultStyleResource(defStyleRes)

.build()

.callTargetMethodsNow();

}

而已。 现在,当您从XML实例化类时,Spyglass伴侣会解释属性并进行所需的方法调用。 例如,如果我们膨胀以下布局,则将使用"Hello, World!"作为参数调用setTitle。

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

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

android:width="match_parent"

android:height="match_parent">

android:width="match_parent"

android:height="match_parent"

app:title="Hello, World!"/>

框架不仅限于字符串资源,还有许多不同的注释用于处理其他资源类型。 如果您的方法具有多个参数,它还具有用于定义默认值和传递占位符值的注释。

有关更多信息和示例,请查看Github仓库。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值