zoukankan      html  css  js  c++  java
  • 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));
    } 
  • 相关阅读:
    CPP标准模板库 随笔
    C++ Concurrency In Action 一些重点
    标准模板库(STL)
    单链表常见操作
    android三大组件之Intent
    数组k平移三种方法(java)
    java中空字符串、null的区别
    java最大最小堆
    java学习笔记之基础知识
    笔试题集锦
  • 原文地址:https://www.cnblogs.com/yongdaimi/p/6170616.html
Copyright © 2011-2022 走看看