【问题标题】:Drawable resource from custom attribute来自自定义属性的可绘制资源
【发布时间】:2013-07-29 22:03:14
【问题描述】:

是否有可能在某些自定义属性中从可绘制文件夹中获取资源,所以我可以写:

<com.my.custom.View
    android:layout_height="50dp"
    android:layout_width="50dp"
    ...
    my_custom:drawableSomewhere="@drawable/some_image" />

然后在我的自定义视图类中使用 drawable 简单地执行操作?

【问题讨论】:

    标签: android xml drawable


    【解决方案1】:

    其实有一种属性格式叫做“reference”。所以你会在你的自定义视图类中得到类似的东西:

    case R.styleable.PMRadiogroup_images:
                        icons = a.getDrawable (attr);
                        break;
    

    虽然在 attrs.xml 中有这样的内容:

    <attr name="images" format="reference"/>
    

    其中“a”是一个 TypedArray,您可以从视图构造函数获取的属性中获取。

    这里有一个很好的类似答案:Defining custom attrs

    【讨论】:

    【解决方案2】:

    查看 EdgarK 的回答;它更好。 (我不能删除它,因为它是公认的答案)

    这能回答你的问题吗?

    "你可以使用 format="integer"、drawable 的资源 id 和 AttributeSet.getDrawable(...)。"

    (来自https://stackoverflow.com/a/6108156/413254

    【讨论】:

      【解决方案3】:

      我用过这个,它适用于 kotlin(编辑粘贴完整类)

      class ExtendedFab(context: Context, attrs: AttributeSet?) :
      LinearLayout(context, attrs) {
      
      init {
      
          LayoutInflater.from(context).inflate(R.layout.component_extended_fab, this, true)
          attrs?.let {
      
              val styledAttributes = context.obtainStyledAttributes(it, R.styleable.ExtendedFab, 0, 0)
              val textValue = styledAttributes.getString(R.styleable.ExtendedFab_fabText)
              val fabIcon = styledAttributes.getDrawable(R.styleable.ExtendedFab_fabIcon)
      
              setText(textValue)
              setIcon(fabIcon)
              styledAttributes.recycle()
          }
      }
      
      /**
       * Sets a string in the button
       * @param[text] label
       */
      fun setText(text: String?) {
          tvFabLabel.text = text
      }
      
      /**
       * Sets an icon in the button
       * @param[icon] drawable resource
       */
      fun setIcon(icon: Drawable?) {
          ivFabIcon.setImageDrawable(icon)
      }
      }
      

      使用这个属性

      <declare-styleable name="ExtendedFab">
          <attr name="fabText" format="string" />
          <attr name="fabIcon" format="reference" />
      </declare-styleable>
      

      这是布局

       <com.your.package.components.fab.ExtendedFab
              android:id="@+id/efMyButton"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_margin="16dp"
              android:elevation="3dp"
              android:clickable="true"
              android:focusable="true"
              app:fabIcon="@drawable/ic_your_icon"
              app:fabText="Your label here" />
      

      【讨论】:

      • 不适用于 Android 6 设备!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-15
      • 1970-01-01
      • 2011-06-22
      • 2011-09-14
      相关资源
      最近更新 更多