如何在Android的xml上创建自定义属性?

Teb*_*bam 29 java android

我们在项目中有一个带有"Key"元素的键盘,这个Key元素具有android:codes ="119",android:keyLabel ="w"等属性.

我的问题是如何包含一个自定义属性,如"android:alternativeKeyLabel"来做其他事情.

JPM*_*aes 54

此链接提供了一个肤浅的解释:http: //developer.android.com/guide/topics/ui/custom-components.html

考虑到你有一个继承自KeyboardView/View的CustomKeyboard:

  1. 在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>
Run Code Online (Sandbox Code Playgroud)
  1. 在自定义组件中创建构造函数,覆盖接收属性集的默认构造函数,因为在加载布局时将调用此属性集.

    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();
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在布局文件中,添加自定义组件和资源链接.

 <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>
Run Code Online (Sandbox Code Playgroud)

  • 当尝试使用来自库的自定义属性的自定义视图(例如,自定义Facebook登录按钮)时,使用自定义属性的布局必须使用命名空间URI"http://schemas.android.com/apk/res-auto"而不是URI包括应用程序包名称.在构建时,此URI将替换为特定于应用程序的URI.也就是说,"xmlns:app ..."应替换为:xmlns:custom ="http://schemas.android.com/apk/res-auto"并且,在使用时,"app:custom_property ..." with:"custom:custom_property ..."Obs.:只有ADT修订版17+增加了对此的支持. (7认同)
  • @JPMagalhaes你是个天才.简单直接.我只需添加行`xmlns:custom ="http://schemas.android.com/apk/res-auto"`,**以及**`xmlns:android ="http:// schemas. android.com/apk/res/android"`,然后我可以从我正在使用的库中添加属性,例如我的自定义小部件中的`custom:pstsUnderlineColor ="#ffffff".非常感谢! (2认同)

von*_*ono 8

出于任何其他目的,可以使用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>
Run Code Online (Sandbox Code Playgroud)

然后在我的类构造函数中:

public CustomView(Context context, AttributeSet attrs) {
    String bar = attrs.getAttributeValue(null, "foo");
    Log.d("CustomView", "foo=" + bar);
}
Run Code Online (Sandbox Code Playgroud)


fup*_*uck 0

android:keyLabel 是 Keyboard.Key 类为键盘上的每个键使用的众多 XML 属性之一。android:keyLabel 是您想要标记键的内容(如上面的“w”)。这些属性是为类预先定义的。“w”不是,但 android:keyLabel 是。如果您可以创建 android:alternativeKeyLabel 您希望该类用它做什么?我认为也许你应该尝试进一步解释你想要实现的目标。