如何创建支持Android中所有视图的自定义属性



在Android中,XML用于设计用户界面。Android为每个标签提供一组属性[ex:id,layout_width,layout_height]。

但是,是否有可能为Android中通常的所有标签添加一个新属性。

 <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/search_result"
    extra = "This is search field"
    useOfThisTag = "Search Operation"
    etc...
 />

这取决于您想实现的目标。官方Android实施中没有全球属性。您提到的是两种:

  1. 查看属性:ID,标签,背景,填充等。这些都是通过视图类解释的,并且似乎是全局>

  2. 布局属性:宽度,高度,边距等。该组始终通过父布局来解释。如果您在Linearlayout中放置一个视图,则可以使用Linearlayout.layoutparams声明的属性。

如果您想添加一个真正的全局属性,则可以尝试使用书法的方法。这是一个库,为所有文本视图添加了对自定义字体的支持。他们的作者使用自定义上下文处理器和资源解析器来拦截书法的属性,同时解析视图标签。

这与包含,片段,布局和合并标签的功能非常相似,但在属性级别上。这些标签是全局的,并且在Layoutinflater内部进行解析和处理。

create attr.xml 自定义属性的文件

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ColorOptionsView">
        <attr name="titleText" format="string" localization="suggested" />
        <attr name="valueColor" format="color" />
    </declare-styleable>
</resources>

activity_main.xml :包含textView的布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
<!-- define new name space for your attributes -->
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
<!-- Assume that this is your new component. It uses your new attributes -->
        <com.example.vishva.CustomTextview
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            custom:titleText="Background color"
            custom:valueColor="@android:color/holo_green_light"
             />
</LinearLayout>

您还必须创建扩展TextView类的CustomTextView类

最新更新