2012-12-07 34 views
8

Cố gắng chuyển thuộc tính tùy chỉnh từ bố cục gốc sang bố cục con.thuộc tính tùy chỉnh monodroid/xamarin trống bằng cách sử dụng ObtainStyledAttributes

TypedArray được trả về từ ObtainStyledAttributes() dường như không có giá trị tùy chỉnh tương ứng cho thuộc tính tùy chỉnh mà tôi đã tạo, mặc dù tôi có thể ánh xạ ID của chúng đến các giá trị trong 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" /> 

Xem Class:

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 

Trả lời

6

Tôi nghĩ vấn đề nằm với cách bạn định xmlns:custom của bạn không gian tên. Bạn cần phải thêm không gian tên ứng dụng của bạn ở phần cuối của chuỗi của bạn đã có như vậy:

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

Bạn cũng cần phải có một AndroidManifest.xml định nghĩa cho dự án Android của bạn, nơi bạn đã xác định không gian tên tương tự.

Ngoài ra các dòng:

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

Nhìn một chút xa lạ với tôi và tôi sẽ chỉ cần viết:

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

Đặc biệt nếu bạn không sử dụng styleAttrs sau này.

EDIT: kể từ Android SDK rev 17 có thể sử dụng:

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

thay vì phải viết toàn bộ không gian tên.

Các vấn đề liên quan