我需要实现自己的属性,例如com.android.R.attr
在官方文档中找不到任何内容,因此我需要有关如何定义这些属性以及如何从我的代码中使用它们的信息。
#1楼
Qberticus的回答很好,但是缺少一个有用的细节。 如果要在库中实现这些,请替换:
xmlns:whatever="/apk/res/org.example.mypackage"
与:
xmlns:whatever="/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 =
"/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 = att
如果觉得《java 自定义属性 定义自定义属性》对你有帮助,请点赞、收藏,并留下你的观点哦!