Can a drawable shape have it's size set to fil

2020-08-09 05:18发布

问题:

Is it valid for a drawable shape in Android to use fill_parent for it's size?

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

<solid
        android:color="#666666"/>

<size
        android:width="fill_parent"
        android:height="fill_parent"/>
</shape>

EDIT

This for the background of ImageButton views. I want the icon for the button to have a circle behind it, but I don't always know what the size of the button will be (different sizes per layout).

回答1:

Not really. Not using a ShapeDrawable alone. If you go through the ShapeDrawable document, you will see (you are already using them in the tag) that the only valid attributes there are px, dp, sp, in and mm

A quote from the doc: android:width="...."

Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters) This is true for the attribute: android:height

This is speculation on my part, but I suspect why the fill_parent attribute value will not work is because a ShapeDrawble, unlike an XML Layout file will not have a parent container.

Leaving out the <size.... /> attribute entirely and setting the layout_width and layout_height on a Widget that will reference the said ShapeDrawable is the only option I suspect (if the fill_parent is to be honored).



回答2:

I don't know which API level this took effect, but per the Shape drawable documentation, it will be scaled proportionately to fit the view. So you can, for example, put width=1dp and height=1dp. See https://stuff.mit.edu/afs/sipb/project/android/docs/guide/topics/resources/drawable-resource.html#Shape



回答3:

How do you plan to use this shape? You can set it as src or background for any view and set view height in "fill_parent" - it's more usual way.



回答4:

You can't do it from the xml file, but you can do it from the java file. Just use

public final void resize (float width, float height)