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

时间:2016-03-18 15:48:08

标签: java android

我在xml中有自己的自定义组件,就像这样编写

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

ATTRS:

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

1 个答案:

答案 0 :(得分:1)

鉴于前两个文件,您必须进行以下更改才能使其正常工作:

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

相关问题