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

android 参数 attrs.xml,android – 定义自定义attrs传统的方法充满了样板代码和笨拙的资源处理。这就是我制作Spyglass框架的原因。为了演示它是如何工作的,这里有一个示例,展示如何创建一个显示字符串标题的自定义视图。第1步:创建自定义视图类。publicclassCustomViewextendsFrameLayout{privateTextViewtitleView;publicCustomView(Contextcont…

大家好,欢迎来到IT知识分享网。android 参数 attrs.xml,android - 定义自定义attrs

传统的方法充满了样板代码和笨拙的资源处理。 这就是我制作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://yundeesoft.com/15172.html

(0)

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信