我在 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?
最佳答案
给定前两个文件,您必须进行以下更改才能使其正常工作:
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
丢弃。
关于java - 在自定义组件中获取 android 特定属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36088728/