首先自定义view需要重写onDraw方法,处理wrap_content/padding 的问题
加入自定义参数:
- attrs.xml中
<resources>
<declare-styleable name="MyHorizontalListView">
<attr name="myDividerWidth" format="dimension" />
<attr name="android:divider" />
<attr name="android:requiresFadingEdge" />
<attr name="android:fadingEdgeLength" />
</declare-styleable>
</resources>
- 代码中获取数值
private void retrieveXmlConfiguration(Context context, AttributeSet attrs) {
if (attrs != null) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyHorizontalListView);
// Get the provided drawable from the XML
final Drawable d = a.getDrawable(R.styleable.MyHorizontalListView_android_divider);
if (d != null) {
// If a drawable is provided to use as the divider then use its intrinsic width for the divider width
setDivider(d);
}
// If a width is explicitly specified then use that width
final int dividerWidth = a.getDimensionPixelSize(R.styleable.MyHorizontalListView_myDividerWidth, 0);
if (dividerWidth != 0) {
setDividerWidth(dividerWidth);
}
a.recycle();
}
}
- 使用自定义View
<com.xxtoutiao.xxtt.view.MyHorizontalListView
android:id="@+id/home_myHorizontalListView"
android:layout_width="match_parent"
android:layout_height="44dp"
android:layout_toRightOf="@+id/home_avatar"
android:layout_toLeftOf="@+id/set_channel"
app:tabMode="scrollable" />
xml中:xmlns:app=http://schemas.android.com/apk/res-auto
app:是自定义属性的前缀,当然可以换其他名字,但是CircleView中使用自定义属性了,比如:app:circle_color= “@color/light_green”
也可以写为
xmlns:app=http://schemas.android.com/apk/com.xxtoutiao.xxtt
自定义view不要忘记wrap_content时的处理