soc*_*qwe 6 xml android android-custom-view
我想用自己的xml属性创建自定义视图.我想指定一个在我的自定义xml视图中膨胀的标题布局,如下所示:
<com.example.MyCustomWidget
android:layout_width="match_parent"
android:layout_height="match_parent"
app:headerLayout="@layout/my_header"
/>
Run Code Online (Sandbox Code Playgroud)
这是可能的,如何从中获取布局资源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>
Run Code Online (Sandbox Code Playgroud)
Bla*_*laz 17
首先,您必须创建自定义字段.哟通过添加以下代码来做到这一点 res/values/attrs.xml
<declare-styleable name="MyCustomView">
<attr name="headerLayout" format="reference" />
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)
然后在自定义视图中,您可以在构造函数中获取此值
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();
}
...
}
Run Code Online (Sandbox Code Playgroud)
从这里你可以膨胀headerLayout与LayoutInflater
| 归档时间: |
|
| 查看次数: |
3706 次 |
| 最近记录: |