[英]Android custom attributes not showing
我看过很多帖子,有人想知道如何为自定义组件获取自定义属性,但这不是我的问题。 我创建了一个自定义组件,我正在尝试添加属性,但是当我在我的 xml 文件顶部添加命名空间时,它只找到两个随机的自定义属性“paddingEnd”和“paddingStart”。
<resources>
<declare-styleable name="menu_item_attrs">
<attr name="imageId" format="integer" />
<attr name="menuText" format="string" />
</declare-styleable>
</resources>
这是 attrs.xml 文件。
public MenuListItem(Context context, AttributeSet set) {
super(context, set);
TypedArray a = context.obtainStyledAttributes(set, R.styleable.menu_item_attrs);
if (a == null) {
return;
}
CharSequence s = a.getString(R.styleable.menu_item_attrs_menuText);
if (s != null) {
// do something
}
}
这是我的自定义类中的构造函数。
<LinearLayout
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="@+id/expanding_layout"
android:background="#029eed">
<aaron.testappanim.MenuListItem
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
</LinearLayout>
这是我正在使用的组件。 我想向“imageId”和“menuText”添加值,但它们不可用。 唯一显示的是与填充相关的内容,如下所示。
有什么想法吗?
找到了解决办法。
碰巧的是,您需要具有与类名相同的样式名称。
<resources>
<declare-styleable name="MenuListItem">
<attr name="my_custom_attribute" format="integer" />
</declare-styleable>
</resources>
在这种情况下,关于这个主题的许多帖子都是错误的,因为我可以看到很多样式名称完全不同。
希望这可以阻止其他人落入这个陷阱。
干杯
我的解决方案是:在 attr.xml 文件中,您可能已按如下方式声明您的自定义属性
<declare-styleable name="IDEditText"> <attr name="customFont" format="string"/> </declare-styleable>
这里, declare-styleable
的 name 字段必须是自定义视图的名称。 然后它会显示在建议中。
在我的情况下,我的自定义视图名称是IDEditText
,因此可以declare-styleable
名称 =“IDEditText”
虽然这篇文章有点旧,但为了提供信息,我将分享我的案例。
我定义了一个名为attrs.xml
的自定义属性文件以与 MaterialCardView 一起使用:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="DeviceMaterialCardView">
<attr name="state_none" format="boolean"/>
<attr name="state_favorite" format="boolean"/>
<attr name="state_dragging" format="boolean"/>
</declare-styleable>
</resources>
我使用拖动 attr 使用此选择器更改 cardview 的笔触颜色:
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:himtec="http://schemas.android.com/apk/res-auto">
<item android:color="?attr/colorSecondary" himtec:durum_surukle="true"/>
<item android:color="?attr/colorSecondary" android:state_activated="true"/>
<item android:alpha="0.2" android:color="?attr/colorOnBackground"/>
</selector>
最后我有一个名为DeviceMaterialCardView
的自定义类。 现在自定义属性与自定义类同名。 但是我在编译him_stroke_color
xml 文件时遇到编译错误:
/home/Projeler/PK-BLE-RF/Android/Uygulama/PK0101BLE/app/src/main/res/color/him_stroke_color.xml:6: AAPT: 错误: 属性 com.himtec.himtec_kontrol:state_dragging 未找到。
我仍然被卡住,无法弄清楚如何解决这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.