美文网首页
自定义控件:分割线(Divider)

自定义控件:分割线(Divider)

作者: 好学人 | 来源:发表于2020-02-22 02:56 被阅读0次

    自定义属性

    目录:res/attrs.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <declare-styleable name="Divider">
            <attr name="android:orientation" />
            <attr name="android:background" />
        </declare-styleable>
    </resources>
    

    代码实现

    /**
     * 自定义控件:分割线
     */
    public class Divider extends View {
    
        private int orientation;
        private Drawable background;
    
        public Divider(Context context) {
            this(context, null);
        }
    
        public Divider(Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
            TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.Divider);
            orientation = attributes.getInt(R.styleable.Divider_android_orientation, 0);
            background = attributes.getDrawable(R.styleable.Divider_android_background);
            background = (background == null) ? new ColorDrawable(Color.WHITE) : background;
            attributes.recycle();
        }
    
        @Override
        protected void onAttachedToWindow() {
            super.onAttachedToWindow();
            ViewGroup.LayoutParams layoutParams = getLayoutParams();
            int wrapContent = ViewGroup.LayoutParams.WRAP_CONTENT;
            int matchParent = ViewGroup.LayoutParams.MATCH_PARENT;
    
            int width = layoutParams.width;
            int height = layoutParams.height;
    
            if (orientation == LinearLayout.HORIZONTAL) {
                // 水平方向
                layoutParams.width = (width == wrapContent) ? matchParent : width;
                layoutParams.height = (height == wrapContent) ? 1 : height; // 1px
            } else {
                // 垂直方向
                layoutParams.width = (width == wrapContent) ? 1 : width; // 1px
                layoutParams.height = (height == wrapContent) ? matchParent : height;
            }
            this.setBackground(background);
            this.requestLayout();
        }
    }
    
    

    使用示例

    <com.haoxueren.view.Divider
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorWhite"
        android:orientation="horizontal"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="@id/webViewLayout" />
    

    相关文章

      网友评论

          本文标题:自定义控件:分割线(Divider)

          本文链接:https://www.haomeiwen.com/subject/agukqhtx.html