2012-04-12 8 views
3

RelativeLayoutから継承するカスタムコンポーネントを作成しようとしています。私のXMLレイアウトファイルでカスタムコンポーネントのandroid:srcの読み方

、私が持っている:

<Mycomponent 
    android:src="@drawable/my_test_image"> 
     <TestView> 
</Mycomponent> 

私の質問は、私はMyComponentののコンストラクタでDrawableのクラスを作成することができる方法ですか?

私はImageViewのソースコードを読もうとしましたが、いくつかのアンドロイドInternal.Rが試したようです。

私のコードでそれを行うことはできますか。

ありがとうございます。

+0

カスタムビューのコンストラクタで描画可能な 'my_test_image'を取得しますか? – Luksprog

+0

はい。レイアウトXMLファイルで 'android:src'を読み込んでDrawableオブジェクトを作成します。 – michael

答えて

14

私はLuksprogが、それは間違っている、私はちょうど属性セットを呼び出し、styleableずにカスタムコンポーネント "SRC" のデータを、あなたにアクセスするための簡単な解決策を持っていると思う:

attrs.getAttributeResourceValue( "http://schemas.android.com/apk/res/android"、 "SRC" 、0)。

ここで私の例では、ビットマップサイズをもっと安くすることができます、jeje。

public CustomView(Context context, AttributeSet attrs) { 
super(context, attrs); 
int src_resource = attrs.getAttributeResourceValue("http://schemas.android.com/apk/res/android", "src", 0); 
this.setImageBitmap(getDrawable(getResources(),src_resource)); 
} 

public static Bitmap getDrawable(Resources res, int id){ 
    return BitmapFactory.decodeStream(res.openRawResource(id)); 
} 

今、あなたはこのようなXMLで何かがあります:私はまた、あなたがこれを行うことができます提案を見てきました

<com.example.com.jfcogato.mycomponent.CustomView 
    android:id="@+id/tAImageView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:src="@drawable/big_image_example"/> 
+1

'this.setImageDrawable(getResources()。getDrawable(src_resource))' ...すべてのタイプのドロワーブルをサポートするために使用する必要があります。あなたのコードは画像のみをサポートしています。 –

1

を...私の経験で

int attributeIds[] = { android.R.attr.src }; 
    TypedArray a = context.obtainStyledAttributes(attributeIds); 
    int resourceId = a.getResourceId(0, 0); 
    a.recycle(); 

このコードはコンパイルされますが、実行時には0が返されます。

ですから、上記のjfcogatoさんの答えに従ってください。

関連する問題