2013-08-29 19 views
5

自分のカスタムビューを作成しましたが、カスタム属性を設定したいと思います。別のビューのIDを属性として渡したいと思います。カスタム属性を持つAndroidカスタムビュー

カスタム表示attrsに:私は私のカスタムビューを使用

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <declare-styleable name="IdNumber"> 
     <attr name="firstName" format="integer"/> 
     <attr name="lastName" format="integer"/> 
     <attr name="address" format="integer"/> 
     <attr name="birthDate" format="integer"/> 
    </declare-styleable> 
</resources> 

レイアウト:

<?xml version="1.0" encoding="utf-8"?> 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:custom="http://schemas.android.com/apk/res-auto" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <EditText 
     android:id="@+id/display_name" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:inputType="text" 
     android:layout_centerHorizontal="true" 
     android:tag="name" 
     android:ems="10" /> 

    <EditText 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:inputType="number" 
     android:ems="10" 
     android:id="@+id/id_number" 
     android:layout_centerHorizontal="true" 
     android:layout_below="@id/display_name"/> 

    <ge.altasoft.custom_views.IdNumber 
     android:id="@+id/custom_id_number" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_centerHorizontal="true" 
     android:layout_below="@id/id_number" 
     android:paddingLeft="35dip" 
     custom:firstName="@id/display_name"/> 


</RelativeLayout> 

iの属性値を取得したいカスタムビュークラスのコンストラクタ、:

public IdNumber (Context context, AttributeSet attrs) { 
     super(context, attrs); 
     initViews(); 

     TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.IdNumber); 
     final int N = a.getIndexCount(); 
     for(int i = 0; i < N; i++){ 
      int attr = a.getIndex(i); 
      switch(attr){ 
       case R.styleable.IdNumber_firstName: 
        int firstNameViewID = a.getInteger(attr, -1); 
        break; 
      } 
     } 
     a.recycle(); 
    } 

問題は、int firstNameViewID = a.getInteger(attr, -1);がViewのIDではなく0にすぎないことです。

custom:firstName="@id/display_name" < < <ここでは何かが間違っているはずですが、何が間違っているのか分かりません。私はカスタム属性にいくつかの整数値を割り当てると動作しますが、Id-sでは動作しません。

アドバンスでお世話になりました。

答えて

12
<attr name="firstName" format="refernce"/>にごstyleable変更、それはあなたの <attr name="firstName" format="reference"/> そして、あなたのコードを使用して int firstNameViewID = a.getResourceId(attr, -1);

を定義・ホープこのヘルプを変更

中!

+0

助けてくれてありがとう。 – Jilberta

0

使用custom:firstName="@+id/display_name"、代わりに整数

+0

私は既に使用していますが、それは役に立ちません。 – Jilberta

+0

とidを取得している間は答えがa.getReference() –

+1

ありがとうございますが、a.getResourceId(attr、-1)が役に立ちました。 – Jilberta

関連する問題