我们的项目中有一个带有“Key”元素的键盘,这个Key元素有android:codes="119", android:keyLabel="w"等属性。
我的问题是如何包含一个自定义属性,如“android:alternativeKeyLabel”来做其他事情。
最佳答案
这个链接给出了一个肤浅的解释: http://developer.android.com/guide/topics/ui/custom-components.html
考虑到您有一个继承自 KeyboardView/View 的 CustomKeyboard:
- 在 res/values/attrs.xml 文件中创建您的自定义属性(如果文件不存在,则创建该文件):
<?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>
关于java - 如何在 Android 的 xml 上创建我的自定义属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2029719/