سؤال

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?

هل كانت مفيدة؟

المحلول

The layout editor does not always pick up <declare-styleable> attributes straight away. Restarting eclipse fixed the problem. The above code was all correct; the package name should obviously be the package of the project for the namespace in the layout, and the custom View will use generated values from R.styleable.

Known issue:

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top