温馨提示×

在Android中以编程方式创建视图时如何传递AttributeSet

小云
133
2023-09-27 06:42:54
栏目: 编程语言

在Android中,可以使用以下方法将AttributeSet传递给自定义视图:

  1. 使用自定义构造函数:为自定义视图创建一个构造函数,该构造函数接受一个Context对象和一个AttributeSet对象作为参数。在构造函数中,通过调用super方法将AttributeSet传递给父类构造函数。
public class CustomView extends View {
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
// 进行其他初始化操作
}
}
  1. 通过LayoutInflater的inflate()方法:如果自定义视图是通过布局文件加载的,可以使用LayoutInflater的inflate()方法将AttributeSet传递给视图。
LayoutInflater inflater = LayoutInflater.from(context);
CustomView customView = (CustomView) inflater.inflate(R.layout.custom_view, parentView, false);

在布局文件中,可以通过在根视图上设置自定义属性来传递AttributeSet。

<com.example.CustomView
android:layout_width="match_parent"
android:layout_height="wrap_content"
custom:customAttribute="value" />
  1. 使用Theme中的属性:如果要从Theme中获取属性的值,并将其传递给自定义视图,可以使用TypedArray对象。
TypedArray typedArray = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.CustomView, 0, 0);
int customAttributeValue = typedArray.getInt(R.styleable.CustomView_customAttribute, defaultValue);
typedArray.recycle();

在这种情况下,需要在自定义视图的attr.xml文件中定义自定义属性。

<resources>
<declare-styleable name="CustomView">
<attr name="customAttribute" format="integer" />
</declare-styleable>
</resources>

0