2012-04-12 42 views
3

我正在嘗試創建一個從RelativeLayout繼承的自定義組件。如何在我的自定義組件中讀取android:src

在我的XML佈局文件,我有:

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

我的問題是如何在爲MyComponent的構造函數創建一個可繪製類?

我試圖閱讀ImageView的源代碼,但它似乎嘗試了一些android Internal.R。

無論如何,我可以在我的代碼中做到這一點。

謝謝。

+0

你想在自定義視圖的構造函數中獲取可繪製的'my_test_image'嗎? – Luksprog 2012-04-12 18:45:27

+0

是的。我想通過閱讀佈局xml文件中的'android:src'來創建一個Drawable對象。 – michael 2012-04-12 19:03:07

回答

14

我覺得Luksprog這是錯的,我有一個簡單的解決方案來訪問您的自定義組件 「SRC」 數據,而無需設置樣式,只是在調用的AttributeSet:

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))' ...應該用來支持所有類型的drawable。你的代碼只支持圖片。 – 2015-01-17 19:53:54

1

我也看到了建議,你可以做到這一點...

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

在我的經驗,這代碼編譯但在運行時返回0。

所以是的...去與jfcogato的答案上面。

相關問題