我需要实现自己的属性,例如 com.android.R.attr
在官方文档中找不到任何内容,因此我需要有关如何定义这些属性以及如何从我的代码中使用它们的信息。
我需要实现自己的属性,例如 com.android.R.attr
在官方文档中找不到任何内容,因此我需要有关如何定义这些属性以及如何从我的代码中使用它们的信息。
Answers:
当前,最好的文档是源。您可以在这里(attrs.xml)进行查看。
您可以在顶部<resources>元素或元素内部定义属性<declare-styleable>。如果要在多个位置使用attr,请将其放在根元素中。注意,所有属性共享相同的全局名称空间。这意味着,即使您在<declare-styleable>元素内部创建新属性,也可以在元素外部使用它,并且您不能创建具有相同名称,不同类型的另一个属性。
一个<attr>元素有两个XML属性name和format。name让您称呼它,这就是您最终在代码中引用它的方式,例如R.attr.my_attribute。该format属性可以具有不同的值,具体取决于所需属性的“类型”。
您可以使用格式设置为多种类型|,例如,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();
}
结束。:)
View:github.com/commonsguy/cw-advandroid/tree/master/Views/…–
                    xmlns:my="http://schemas.android.com/apk/lib/my.namespace"-不复制attrs.xml。请注意,名称空间URI路径必须是/ apk / * lib *而不是/ apk / res。
                    apk/lib技巧对我自定义属性(来自图书馆项目的参考格式)不起作用。什么做的工作是使用apk/res-auto,如建议stackoverflow.com/a/13420366/22904略低于以及在stackoverflow.com/a/10217752
                    enum和之间的主要区别flag:前者让我们选择一个并且只有一个值,后者让我们结合多个值。我在这里用类似的问题写了一个更长的答案,现在发现这个问题后,我想我可以链接到该问题。
                    a.recycle()在这里释放内存非常重要
                    Qberticus的回答很好,但是缺少一个有用的细节。如果要在库中实现这些,请替换:
xmlns:whatever="http://schemas.android.com/apk/res/org.example.mypackage"
与:
xmlns:whatever="http://schemas.android.com/apk/res-auto"
否则,使用该库的应用程序将出现运行时错误。
上面的答案涵盖了所有细节,除了两点。
首先,如果没有样式,则将使用(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);
}
notifyChanged()首选项的onDialogClosed方法。传统方法充满了样板代码和笨拙的资源处理。这就是为什么我制作了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存储库。
android:title="@{"Hello, world!"}"。
                    如果您format从attr元素中省略属性,则可以使用它来引用XML布局中的类。
Refactor > Rename 作品Find Usages 作品不要format在... / src / main / res / values / attrs.xml中指定属性
<?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()
            }
        }
    }