有几个构造函数可用于定义ImageView。 例如
1) public ImageView (Context context)
2) public ImageView (Context context, AttributeSet attrs)
3) public ImageView (Context context, AttributeSet attrs, int defStyle)**
我很困惑使用第二种和第三种类型的构造函数。 基本上我不知道要通过什么代替 AttributeSet。 请提供编码示例。
答案 0 :(得分:2)
这些构造函数在View
文档中定义。以下是View(Context, AttributeSet, int)
的参数说明:
<强>参数强>
- context 运行视图的上下文,通过它可以访问当前主题,资源等。
- attrs 正在使视图膨胀的XML标记的属性。
- defStyle 要应用于此视图的默认样式。如果为0,则不应用任何样式(超出主题中包含的样式)。这可能 要么是属性资源,要从中检索其值 当前主题,或明确的样式资源。
值得注意的是,如果您没有要传递的属性,可以传递null
代替AttributeSet
。
在AttributeSet
的编码方面,这里有一些我用于自定义TextView
类的代码:
public EKTextView(Context context, AttributeSet attrs) {
super(context, attrs);
// ...
if (attrs != null) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LocalTextView);
determineAttrs(context, a);
}
// ...
}
private void determineAttrs(Context c, TypedArray a) {
String font = a.getString(R.styleable.fontName);
if (font != null)
mTypeface = Typeface.createFromAsset(c.getAssets(), "fonts/" + font);
mCaps = a.getBoolean(R.styleable.allCaps, false);
}
如您所见,一旦从属性中获得TypedArray
,您就可以使用its various methods来收集每个属性。您可能想要审核的其他代码是that of View(Context, AttributeSet, int)
或Resources.obtainStyledAttributes(AttributeSet, int[], int, int)
。
答案 1 :(得分:1)
创建imageView的方法,带有上下文的ImageView
ImageView image= new ImageView(context);
此处如果要设置高度,宽度重力等值,则需要设置
image.set****();
根据您需要使用的属性数量而不使用setXXX()方法,。
2.使用属性集 你可以在单独的xml文件中的res / values文件夹中定义属性集,如高度,宽度等,将xml文件传递给getXml()
XmlPullParser parser = resources.getXml(yourxmlfilewithattribues);
AttributeSet attributes = Xml.asAttributeSet(parser);
ImageView image=new ImageView(context,attributes);
您还可以在xml中定义自定义属性。您可以使用AttributeSet类示例
提供的方法来访问它getAttributeFloatValue(int index, float defaultValue)
//返回'index'
处属性的浮点值