android自定義控件(7)-獲取自定義ImageView的src屬性


 

創建一個自定義組件,繼承 ImageView。
在我的 xml 布局文件中是這樣設置的:

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

如何在 Mycomponent 的 constructor 里創建一個 Bitmap類?

首先想查看 ImageView 的源代碼,但是 它是Android的內部代碼,我們無法這樣使用。

  TypedArray a = context.obtainStyledAttributes(attrs,
                com.android.internal.R.styleable.ImageView, defStyle, 0);
  Drawable d = a.getDrawable(com.android.internal.R.styleable.ImageView_src);

后來發現有2種解決方案。

 

1:定義過一個自己的屬性(例:img),再用下面的方法得到

 

TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.ButtonPreference, defStyle, 0); 
Drawable drawable = a.getDrawable(R.styleable.MyComponent_img); //button的名稱
a.recycle();

 

2:通過默認屬性獲得:

public Mycomponent (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));
} 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM