布局编辑器不会将可设置属性传递给自定义View类

时间:2014-03-28 10:40:15

标签: android graphical-layout-editor declare-styleable

我正在创建一个FixedAspectImageView来解决Android中的问题,即让ImageView设置其视图范围以匹配中包含的图像的宽高比填充任意宽(或高)的可用区域并适当地拉伸图像。在当前版本中,我从布局中发送浮点“比率”参数,但最终我打算检测图像的比例。

但是,我在使用样式属性时遇到问题。我的attrs.xml有这个:

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

我的构造函数如下:

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();
    }
}

(对于末尾带有整数defStyle的那个非常相似),我的布局文件如下所示:

<?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>

我已确定setRatio(Float)有效,因为如果我在源中设置了值,则测量系统可以正常工作。传入的TypedArray没有设置索引。造成这种情况的原因是什么?

1 个答案:

答案 0 :(得分:0)

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

已知问题:

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