前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >android 参数 attrs.xml,android – 定义自定义attrs

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

作者头像
全栈程序员站长
发布2022-09-27 10:18:17
5270
发布2022-09-27 10:18:17
举报
文章被收录于专栏:全栈程序员必看

传统的方法充满了样板代码和笨拙的资源处理。 这就是我制作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仓库。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/183472.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档