How can I create my custom properties on xml for Android?

android, java

Solution

This link gives a superficial explanation: http://developer.android.com/guide/topics/ui/custom-components.html

Considering you have a CustomKeyboard that inherits from KeyboardView/View:

- Create your custom properties in res/values/attrs.xml file (create the file if it does not exist):

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <declare-styleable name="custom_keyboard">
        <attr name="alternative_key_label" format="string" />
    </declare-styleable>

</resources>

Create a constructor in your custom component overriding default constructor that receives the attribute set because this one will be called when the layout is loaded.

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();
}

In your layout file, add your custom component and the link to your resources.

 <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>

Problem

We have in our project a keyboard with "Key" elements, this Key elements have attributes such as android:codes="119", android:keyLabel="w" and so on. My question is how can I include an custom attribute like a "android:alternativeKeyLabel" to do something else.

Original source