定义自定义属性

混江龙づ霸主 提交于 2020-02-27 12:32:30

我需要实现自己的属性,例如com.android.R.attr

在官方文档中找不到任何内容,因此我需要有关如何定义这些属性以及如何从我的代码中使用它们的信息。


#1楼

Qberticus的回答很好,但是缺少一个有用的细节。 如果要在库中实现这些,请替换:

xmlns:whatever="http://schemas.android.com/apk/res/org.example.mypackage"

与:

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

否则,使用该库的应用程序将出现运行时错误。


#2楼

上面的答案涵盖了所有细节,除了两点。

首先,如果没有样式,则将使用(Context context, AttributeSet attrs)方法签名实例化首选项。 在这种情况下,只需使用context.obtainStyledAttributes(attrs, R.styleable.MyCustomView)即可获取TypedArray。

其次,它没有涵盖如何处理资源(数量字符串)。 这些不能使用TypedArray处理。 这是我的SeekBarPreference的代码片段,用于设置首选项摘要,并根据首选项的值将其值格式化。 如果首选项的xml将android:summary设置为文本字符串或字符串源,则将首选项的值格式化为字符串(应该在其中包含%d,以获取该值)。 如果android:summary设置为plaurals资源,则用于格式化结果。

// Use your own name space if not using an android resource.
final static private String ANDROID_NS = 
    "http://schemas.android.com/apk/res/android";
private int pluralResource;
private Resources resources;
private String summary;

public SeekBarPreference(Context context, AttributeSet attrs) {
    // ...
    TypedArray attributes = context.obtainStyledAttributes(
        attrs, R.styleable.SeekBarPreference);
    pluralResource =  attrs.getAttributeResourceValue(ANDROID_NS, "summary", 0);
    if (pluralResource !=  0) {
        if (! resources.getResourceTypeName(pluralResource).equals("plurals")) {
            pluralResource = 0;
        }
    }
    if (pluralResource ==  0) {
        summary = attributes.getString(
            R.styleable.SeekBarPreference_android_summary);
    }
    attributes.recycle();
}

@Override
public CharSequence getSummary() {
    int value = getPersistedInt(defaultValue);
    if (pluralResource != 0) {
        return resources.getQuantityString(pluralResource, value, value);
    }
    return (summary == null) ? null : String.format(summary, value);
}

  • 只是作为示例,但是,如果您想在首选项屏幕上设置摘要,则需要在首选项的onDialogClosed方法中调用notifyChanged()

#3楼

当前,最好的文档是源。 您可以在这里(attrs.xml)进行查看。

您可以在顶部<resources>元素中或<declare-styleable>元素内部定义属性。 如果要在多个位置使用attr,请将其放在根元素中。 注意,所有属性共享相同的全局名称空间。 这意味着,即使您在<declare-styleable>元素内创建一个新属性,也可以在其外部使用它,并且您不能创建具有相同名称,不同类型的另一个属性。

<attr>元素具有两个xml属性nameformatname使您可以称呼它,这就是您最终在代码中引用它的方式,例如R.attr.my_attributeformat属性可以具有不同的值,具体取决于所需属性的“类型”。

  • 参考-如果它引用了另一个资源ID(例如“ @ color / my_color”,“ @ layout / my_layout”)
  • 颜色
  • 布尔值
  • 尺寸
  • 浮动
  • 整数
  • 分数
  • 枚举-通常隐式定义
  • 标志-通常隐式定义

您可以使用|将格式设置为多种类型| ,例如format="reference|color"

enum属性可以定义如下:

<attr name="my_enum_attr">
  <enum name="value1" value="1" />
  <enum name="value2" value="2" />
</attr>

flag属性是相似的,除了需要定义值,以便可以将它们位在一起:

<attr name="my_flag_attr">
  <flag name="fuzzy" value="0x01" />
  <flag name="cold" value="0x02" />
</attr>

除了属性之外,还有<declare-styleable>元素。 这使您可以定义自定义视图可以使用的属性。 您可以通过指定<attr>元素来执行此操作,如果先前已定义该元素,则不指定format 。 如果您想重用android attr,例如android:gravity,则可以使用name ,如下所示。

自定义视图<declare-styleable>

<declare-styleable name="MyCustomView">
  <attr name="my_custom_attribute" />
  <attr name="android:gravity" />
</declare-styleable>

在自定义视图上以XML定义自定义属性时,您需要做一些事情。 首先,您必须声明一个名称空间以找到您的属性。 您可以在根布局元素上执行此操作。 通常只有xmlns:android="http://schemas.android.com/apk/res/android" 。 现在,您还必须添加xmlns:whatever="http://schemas.android.com/apk/res-auto"

例:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:whatever="http://schemas.android.com/apk/res-auto"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

    <org.example.mypackage.MyCustomView
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:gravity="center"
      whatever:my_custom_attribute="Hello, world!" />
</LinearLayout>

最后,要访问该自定义属性,通常可以在自定义视图的构造函数中进行如下操作。

public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);

  TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView, defStyle, 0);

  String str = a.getString(R.styleable.MyCustomView_my_custom_attribute);

  //do something with str

  a.recycle();
}

结束。 :)


#4楼

传统方法充满了样板代码和笨拙的资源处理。 这就是为什么我制作了Spyglass框架 。 为了演示其工作原理,下面的示例显示了如何制作显示String标题的自定义视图。

步骤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资源文件中定义一个字符串属性:

<resources>
    <declare-styleable name="CustomView">
        <attr name="title" format="string"/>
    </declare-styleable>
</resources>

步骤3:将@StringHandler批注应用于setTitle方法,以告知Spyglass框架在视图放大时将属性值路由到此方法。

@HandlesString(attributeId = R.styleable.CustomView_title)
public void setTitle(String title) {
    titleView.setText(title);
}

现在您的类具有Spyglass批注,Spyglass框架将在编译时对其进行检测并自动生成CustomView_SpyglassCompanion类。

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

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伴随程序将解释属性并进行所需的方法调用。 例如,如果我们增加以下布局,则setTitle将被调用"Hello, World!" 作为论点。

<FrameLayout
    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">

    <com.example.CustomView
        android:width="match_parent"
        android:height="match_parent"
        app:title="Hello, World!"/>
</FrameLayout>

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

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


#5楼

如果您省略了attr元素的format属性,则可以使用它来引用XML布局中的类。

  • 来自attrs.xml的示例。
  • Android Studio知道该类是从XML引用的
      • Refactor > Rename作品
      • Find Usages有效
      • 等等...

不要在... / src / main / res / values / attrs.xml中指定format属性

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="MyCustomView">
        ....
        <attr name="give_me_a_class"/>
        ....
    </declare-styleable>

</resources>

在某些布局文件中使用它... / src / main / res / layout / activity__main_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<SomeLayout
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <!-- make sure to use $ dollar signs for nested classes -->
    <MyCustomView
        app:give_me_a_class="class.type.name.Outer$Nested/>

    <MyCustomView
        app:give_me_a_class="class.type.name.AnotherClass/>

</SomeLayout>

在您的视图初始化代码中解析类... / src / main / java /.../ MyCustomView.kt

class MyCustomView(
        context:Context,
        attrs:AttributeSet)
    :View(context,attrs)
{
    // parse XML attributes
    ....
    private val giveMeAClass:SomeCustomInterface
    init
    {
        context.theme.obtainStyledAttributes(attrs,R.styleable.ColorPreference,0,0).apply()
        {
            try
            {
                // very important to use the class loader from the passed-in context
                giveMeAClass = context::class.java.classLoader!!
                        .loadClass(getString(R.styleable.MyCustomView_give_me_a_class))
                        .newInstance() // instantiate using 0-args constructor
                        .let {it as SomeCustomInterface}
            }
            finally
            {
                recycle()
            }
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!