0

I am creating a FixedAspectImageView to solve the problem in Android of making an ImageView set its view bounds to match the aspect ratio of the image contained within, and also fill an arbitrarily wide (or tall) available area and stretch the image appropriately. In the current version I'm sending a floating point "ratio" parameter from the layout, though eventually I would intend to detect the ratio of the image.

However, I am having trouble with the styleable attributes. My attrs.xml has this:

<resources>
    <!-- other stuff, which bizarrely works -->
    <declare-styleable name="FixedAspectImageView">
        <attr name="ratio" format="float"/>
    </declare-styleable>    
</resources>

My constructor looks like:

public FixedAspectImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
    if(attrs!=null) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FixedAspectImageView);
        if(a.hasValue(R.styleable.FixedAspectImageView_ratio)) {
            setRatio(a.getFloat(R.styleable.FixedAspectImageView_ratio, 1.f));
        }
        a.recycle();
    }
}

(and very similarly for the one with an integer defStyle at the end) and my layout file looks like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:mypackage="http://schemas.android.com/apk/res/com.my.package"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <com.my.package.view.FixedAspectImageView
            android:id="@+id/fixedAspectImageView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scaleType="fitXY"
            android:src="@drawable/picture_of_goatse"
            mypackage:ratio="1.2329" />

    </FrameLayout>

</LinearLayout>

I've determined that setRatio(Float) works, because if I set a value in the source the measurement system works perfectly. The TypedArray being passed in has no indices set. What's causing this?

4

1 回答 1

0

布局编辑器并不总是<declare-styleable>立即获取属性。重启eclipse解决了这个问题。上面的代码都是正确的;包名显然应该是布局中命名空间的项目包,自定义View将使用从R.styleable.

已知问题:

https://code.google.com/p/android/issues/detail?id=52298

于 2014-03-28T10:42:33.610 回答