以下是一个示例代码,演示了如何在Android中自定义视图并从系统attrs.xml文件中绑定值:
public class CustomView extends View {
private String customText;
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
customText = a.getString(R.styleable.CustomView_customText);
a.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 在视图上绘制自定义文本内容
canvas.drawText(customText, 0, 0, new Paint());
}
}
注意:在布局文件中,我们使用了"app"命名空间来引用自定义属性,这是因为我们在attrs.xml中使用了"declare-styleable"标签来定义自定义属性。
通过上述步骤,我们可以在自定义视图中获取并使用从系统attrs.xml文件中绑定的值。在这个示例中,我们在CustomView类中获取了一个名为"customText"的字符串属性,并在视图上绘制了该文本内容。
这只是一个简单的示例,您可以根据自己的需求进行扩展和修改。