【问题标题】:how to specify width and height of a drawable item如何指定可绘制项目的宽度和高度
【发布时间】:2011-09-23 14:50:27
【问题描述】:

您好,是否可以在drawable文件夹中提供drawable.xml中定义的drawable的宽度和高度。

例子:

 <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true"
           android:drawable="@drawable/button_pressed" /> <!-- pressed -->
     <item android:state_focused="true"
           android:drawable="@drawable/button_focused" /> <!-- focused -->
     <item android:drawable="@drawable/button_normal" /> <!-- default -->
 </selector>

我想指定宽度和高度,可能以某种方式使用其中的“scale”标签,我尝试过但没有奏效。这是我的代码:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/icon_ratingstar">
        <scale android:scaleWidth="20" android:scaleHeight="20" android:drawable="@drawable/icon_ratingstar" />
    </item>
</selector>

【问题讨论】:

  • 我能看到的唯一可能起作用的属性是使用类似这样的东西

标签: android layout


【解决方案1】:

layer-list 会有所帮助:这里根据您的要求更改值

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape>
        <size
            android:width="20dp"
            android:height="20dp" />

        <solid android:color="@android:color/black" />
    </shape>
</item>
<item
    android:width="20dp"
    android:height="20dp"
    android:drawable="@drawable/slider_knob" />

【讨论】:

  • 您不能在项目标签内指定宽度和高度,我在文档中没有看到。
  • @user606669 可以,但是API 23以后才支持
  • api 23之前怎么用?
【解决方案2】:

您可以在 API 级别 23 及更高级别中使用属性 widthheight

<item
    android:width="18dp" android:height="18dp"
    android:drawable="@drawable/icon_ratingstar"/>

对于较低的 API 级别,我不知道直接指定 widthheight 的方法。据我所知,最佳做法是缩放可绘制对象。

【讨论】:

    【解决方案3】:

    您可以在&lt;item&gt;标签内指定drawablewidthheight

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true"
           android:width="100dp"
           android:height="20dp"
           android:drawable="@drawable/button_pressed" /> <!-- pressed -->
     <item android:state_focused="true"
           android:width="100dp"
           android:height="20dp"
           android:drawable="@drawable/button_focused" /> <!-- focused -->
     <item android:drawable="@drawable/button_normal" /> <!-- default -->
    

    【讨论】:

    • 以上实际上不起作用。 StateListDrawable(选择器)实际上没有宽度和高度属性。
    • @Sent1nel 绝对是。不过,如果items 背后的内容是这样,则可以将widthheight 与(XML)ShapeDrawable 一起使用。
    • 即使我有一个形状作为可绘制对象的根元素,这似乎也不起作用。我不认为你有一个可行的例子?
    • 老兄,这个答案实际上并没有错。属性 android:widthandroid:height 存在,但仅在 API 级别 23 及更高级别中存在。
    • 您好像忘记删除答案了:)
    猜你喜欢
    • 2010-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 2014-08-07
    • 2017-10-31
    相关资源
    最近更新 更多