2012-12-07 14 views
8

試圖從父佈局的自定義屬性傳遞給子佈局是空的。MonoDroid的/ xamarin自定義屬性使用ObtainStyledAttributes

從ObtainStyledAttributes()返回的TypedArray似乎沒有我創建的自定義屬性的相應自定義值,但我可以將它們的ID映射到Resource.designer中的值。


Attr.xml:

<resources> 
<declare-styleable name="HeaderView"> 
    <attr name="bgcolor" format="color" /> 
    <attr name="testing" format="string" /> 
</declare-styleable> 

Main.xaml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:custom="http://schemas.android.com/apk/res"> 
    <LinearLayout 
     android:orientation="vertical" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent"> 
     <views.HeaderView 
      android:id="@+id/hdrWatchList" 
      android:layout_width="fill_parent" 
      android:layout_height="20.0dp" 
      custom:bgcolor="@color/blue" 
      custom:testing="testing text buddy" /> 

視圖類:

public HeaderView (Context context, IAttributeSet attrs) : 
     base (context, attrs) 
    { 
     int[] styleAttrs = Resource.Styleable.HeaderView; 
     TypedArray a = context.ObtainStyledAttributes(attrs, styleAttrs); 

     string sid = a.GetString(Resource.Styleable.HeaderView_testing); 
     int id = a.GetColor(Resource.Styleable.HeaderView_bgcolor, 555); 

     Log.Info("testing", "resource sid : " + sid); // RETURNS '' 
     Log.Info("testing", "resource id : " + id); // RETURNS DEF 555 

回答

6

我認爲這個問題在於你如何指定你的xmlns:custom命名空間。你需要在字符串的末尾添加應用程序的命名空間的已經有像這樣:

xmlns:custom="http://schemas.android.com/apk/res/my.awesome.namespace" 

您還需要爲您的Android項目,其中定義了相同名稱空間中定義AndroidManifest.xml

也行:

int[] styleAttrs = Resource.Styleable.HeaderView; 
TypedArray a = context.ObtainStyledAttributes(attrs, styleAttrs); 

看起來有點怪我,我會這樣寫:

var a = context.ObtainStyledAttributes(attrs, Resource.Styleable.HeaderView); 

特別是如果你不使用styleAttrs以後。

編輯:由於Android SDK修訂版17,可以使用:

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

,而不必寫入整個名字空間。