我想制作一个具有自己的 xml 属性的自定义 View 。我想指定一个标题布局,它将在我的自定义 xml View 中膨胀,如下所示:
<com.example.MyCustomWidget
android:layout_width="match_parent"
android:layout_height="match_parent"
app:headerLayout="@layout/my_header"
/>
这可能吗?如何从 TypedArray
获取布局资源?
所以最后我想做这样的事情:
class MyCustomWidget extends FrameLayout {
public ProfileTabLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ProfileTabLayout);
int headerLayout = a.getLayout(R.styleable.MyCustomView_headerLayout, 0); // There is no such method
a.recycle();
LayoutInflater.from(context)
.inflate(headerLayout, this, true);
}
}
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyCustomWidget">
<attr name="headerLayout" format="reference" />
</declare-styleable>
</resources>
最佳答案
首先,您必须创建自定义字段。你可以通过将下面的代码添加到 res/values/attrs.xml
<declare-styleable name="MyCustomView">
<attr name="headerLayout" format="reference" />
</declare-styleable>
然后在您的自定义 View 中,您可以在构造函数中获取此值
public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
...
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.MyCustomView,
defStyle, 0
);
try {
int headerLayout = a.getResourceId(R.styleable.MyCustomView_headerLayout, 0);
} finally {
a.recycle();
}
...
}
从这里开始,您可以使用 LayoutInflater
膨胀 headerLayout
关于android - @layout 引用的自定义 xml 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25303979/