在自定义组件中获取Android特定属性

3
我有一个自定义的xml组件,写成这样:

    <com.app.components.CustomComponent
        android:id="@+id/component"
        android:layout_width="96dp"
        android:layout_height="96dp"
        android:scaleType="fitCenter"/>

属性:

<declare-styleable name="CustomComponent">
    <attr name="android:scaleType"/>
</declare-styleable>

我的自定义组件构造函数如下:

@Bind(R.id.imageView) ImageView imageView;
@Bind(R.id.progressBar) ProgressBar progressBar;

public CustomComponent(Context context, AttributeSet attrs) {
    super(context, attrs);

    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FunGuideImageView, 0, 0);

  // how to correctly get scale type defined in xml ?
    int scaleType = a.getValue(R.styleable.CustomComponent_android_scaleType,
            ImageView.ScaleType);


    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.imageview, this, true);
    ButterKnife.bind(view);
    imageView.setScaleType( scaleType );

}

如何在代码中获取xml定义的scaleType并将其设置到imageView上?

CustomComponent 应该继承 View,不是吗? - OneCricketeer
如果您扩展了 ImageView,那么您可以简单地使用 getScaleType() 方法。否则,我认为将您的样式属性命名为与 android: 属性相同的名称并不是一个好主意。 - OneCricketeer
如果我扩展ImageView,我就不能再填充我的自定义xml了。所以目前我正在扩展LinearLayout。 - Datenshi
为什么不呢?据我所知,您正在创建一个包含ProgressBar的自定义ImageView。 - OneCricketeer
在这种情况下,如果我扩展ImageView而不是扩展LinearLayout,则inflater.inflate()会说找不到方法。 - Datenshi
显示剩余3条评论
1个回答

4

根据前两个文件,您需要进行以下更改才能使其正常工作:

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomComponent, 0, 0);
int scaleTypeIndex = a.getValue(R.styleable.CustomComponent_android_scaleType, -1);

然后,你可以通过以下方式获取ImageView.ScaleType数组:
if(scaleTypeIndex > -1) {
    ImageView.ScaleType[] types = ImageView.ScaleType.values();
    ImageView.ScaleType scaleType = types[scaleTypeIndex];
    imageView.setScaleType(scaleType);
}

使用完TypedArray后记得将其清除。


我不得不使用val scaleType: Int = a.getInt(R.styleable.CustomComponent_android_scaleType, -1) ... a.getValue返回一个布尔值...但它可以与a.getInt一起使用。 - jobernas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接