【发布时间】:2011-01-03 00:52:55
【问题描述】:
我们的项目中有一个带有“Key”元素的键盘,这个Key元素有android:codes="119", android:keyLabel="w"等属性。
我的问题是如何包含一个自定义属性,如“android:alternativeKeyLabel”来做其他事情。
【问题讨论】:
我们的项目中有一个带有“Key”元素的键盘,这个Key元素有android:codes="119", android:keyLabel="w"等属性。
我的问题是如何包含一个自定义属性,如“android:alternativeKeyLabel”来做其他事情。
【问题讨论】:
这个链接给出了一个肤浅的解释: http://developer.android.com/guide/topics/ui/custom-components.html
考虑到您有一个继承自 KeyboardView/View 的 CustomKeyboard:
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="custom_keyboard"> <attr name="alternative_key_label" format="string" /> </declare-styleable> </resources>
在您的自定义组件中创建一个构造函数,覆盖接收属性集的默认构造函数,因为在加载布局时会调用这个构造函数。
public CustomKeyboard(Context context, AttributeSet set) {
super(context, set);
TypedArray a = context.obtainStyledAttributes(set,R.styleable.custom_keyboard);
CharSequence s = a.getString(R.styleable.custom_keyboard_alternative_key_label);
if (s != null) {
this.setAlternativeKeyLabel(s.toString());
}
a.recycle();
}
在您的布局文件中,添加您的自定义组件和资源链接。
<Layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res/your.package.ProjectName" .../> ... <your.package.projectname.CustomKeyboard android:id="@+id/my_keyboard" ... app:alternative_key_label="F"> </your.package.projectname.CustomKeyboard> </Layout>
【讨论】:
xmlns:app="http://schemas.android.com/apk/res/your.package.ProjectName 行是访问应用命名空间所必需的。
xmlns:custom="http://schemas.android.com/apk/res-auto",除了 xmlns:android="http://schemas.android.com/apk/res/android",然后我可以从我正在使用的库中添加属性,例如我的自定义小部件中的custom:pstsUnderlineColor="#ffffff"。非常感谢!
对于任何其他目的,可以使用 attrs 构造函数参数检索在 XML 文件中声明的自定义属性。
在我的例子中,我重用了一个偏好自定义对话框,并设置如下:
<?xml version="1.0" encoding="utf-8"?>
<!-- something here -->
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<your.package.projectname.CustomView
foo="bar"
/>
</PreferenceScreen>
然后在我的类构造函数中:
public CustomView(Context context, AttributeSet attrs) {
String bar = attrs.getAttributeValue(null, "foo");
Log.d("CustomView", "foo=" + bar);
}
【讨论】:
您可以为自己的扩展 View 或子类的类创建自定义属性。该过程记录在 Android 开发指南的“创建视图类”部分,标题为“定义自定义属性”:
https://developer.android.com/training/custom-views/create-view#customattr
【讨论】:
android:keyLabel 是 Keyboard.Key 类为键盘上的每个键使用的众多 XML 属性之一。 android:keyLabel 是您要标记密钥的内容(如上面的“w”)。属性是为类预定义的。 “w”不是,但 android:keyLabel 是。如果你可以创建 android:alternativeKeyLabel 你希望这个类用它做什么?我认为也许您应该尝试进一步解释您要完成的工作。
【讨论】: