簡體   English   中英

如何在Android的xml上創建自定義屬性?

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

我們在項目中有一個帶有“Key”元素的鍵盤,這個Key元素具有android:codes =“119”,android:keyLabel =“w”等屬性。

我的問題是如何包含一個自定義屬性,如“android:alternativeKeyLabel”來做其他事情。

此鏈接提供了一個膚淺的解釋: 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> 
  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(); } 
  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> 

出於任何其他目的,可以使用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 Dev Guide“定義自定義屬性”標題下的“創建視圖類”部分中:

https://developer.android.com/training/custom-views/create-view#customattr

android:keyLabel是鍵盤上每個鍵的Keyboard.Key類使用的許多XML屬性之一。 android:keyLabel是你想用鍵標記的鍵(如上面的“w”)。 屬性是為類預定義的。 “w”不是android:keyLabel。 如果你可以創建android:alternativeKeyLabel你期望這個類用它做什么? 我想也許你應該試着進一步解釋你想要完成的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM