自定义View鉴赏

首先自定义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时的处理

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容