2012-03-16 62 views
6

我一直在爲Android設計一個自定義控件,雖然我試圖做什麼建議here似乎有什麼我做錯了。Android自定義控件命名空間問題

這裏是我的代碼,看看是否有人能發現問題:

MyComponent.java

public MyComponent(Context context, AttributeSet attrs) 
{ 
    super(context); 
    TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.MyComponent); 
    CharSequence myId = arr.getString(R.styleable.MyComponent_identifier); 

    if (myId != null) 
    { 
    this.setIdentifier(myId.toString()); 
    } 

    Integer cds = arr.getInteger(R.styleable.MyComponent_cd_number, 0); 

    if(cds != null) 
    { 
    this.setCds(cds); 
    } 

    arr.recycle(); 
} 

attrs.xml

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <declare-styleable name="MyComponent">  
    <attr name="cd_number" format="integer" /> 
    <attr name="identifier" format="string" /> 
    </declare-styleable> 
</resources> 

的main.xml

<TableLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:bgl="http://schemas.android.com/apk/res/my.test.package.components" 
    android:id="@+id/table" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    ... 

    <my.test.package.MyComponent 
    android:id="@+id/hand" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_span="2" 
     bgl:cd_number="4" 
     bgl:identifier="plr"/> 

    ... 

    </TableLayout> 

當我把這個我得到以下錯誤:

錯誤:未發現在包「my.test.package」 錯誤屬性「cd_number」資源標識符:沒有資源標識符發現屬性「標識」中包「my.test.package」

如果我改變我的命名空間是這樣的:

xmlns:bgl="http://schemas.mywhatever.com/apk/res/my.test.package" 

...錯誤去W¯¯ ay和東西運行,但myId爲null,並且cds爲0(默認值!)回到MyComponent.java構造函數上。

我想說這是一個非常基本的錯誤,但我無法發現它,因爲沒有太多的文檔,我決定在這裏問。

在此先感謝!

回答

14

好的構造。我解決了它!

在原來的職位我:

xmlns:bgl="http://schemas.android.com/apk/res/my.test.package 

...但在我的源代碼我有:

xmlns:bgl="http://schemas.android.com/apk/res/my.test.package.components 

...因爲我認爲應該把URI的組件包。

這是錯誤的!

在xmlns上它應該是在Manifest上聲明的應用程序名稱!

當我刪除xmlns中的「components」部分時,它與Manifest中的應用程序名稱「匹配」,並且錯誤消失,當我在調試中運行時,實際上可以看到我傳遞給參數的值在XML中!

希望這可以幫助別人! :-)

UPDATE

後來我有必要控制進入圖書館,再次面對這個問題。看來,當你把組件庫中,並用它在客戶端應用程序,您必須聲明,如下的xmlns:如果你這樣做

xmlns:myns="http://schemas.android.com/apk/res-auto" 

(並宣佈爲Android的依賴庫)的Eclipse(或者它是Android?)將搜索相應的屬性綁定的依賴關係。

+1

偉大的工作研究和提供答案。 res-auto修復正是我所需要的。 – AlanKley 2013-04-15 16:16:01

+0

'res-auto'。你美麗! – darksider474 2014-05-08 09:35:27

+0

什麼是bgl和myns,我怎麼設定這個名字 – Nepster 2015-01-08 13:01:15

0

我有一個類似的問題,原來它被調用不同的構造函數

嘗試與發生在defStyle參數

public MyComponent(Context context, AttributeSet attrs, int defStyle) 
+0

謝謝,觸發器。不幸的是我的問題似乎是另一回事。我定義了你建議的ctor,如果我不改變命名空間,錯誤仍然存​​在。如果我更改xmlns,它將表現相同:新ctor從不調用,myId爲空,並且cds與以前一樣爲0。有什麼想法?任何人? – 2012-03-17 09:18:02