Android使用attr属性自定义view

value中创建对应的attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--VideoItemView自定义属性-->
    <declare-styleable name="VideoItemView">
        <!--是否需要默认封面布局-->
        <attr name="is_need_cover_layout" format="boolean"/>
        <!--默认封面布局左边距-->
        <attr name="cover_layout_padding_left" format="reference|dimension"/>
        <!--默认封面布局右边距-->
        <attr name="cover_layout_padding_right" format="reference|dimension"/>
        <!--是否需要顶部状态栏布局-->
        <attr name="is_need_top_bar" format="boolean"/>
        <!--是否需要底部默认进度条布局,一般在视频列表条目时才需要该布局-->
        <attr name="is_need_default_progress_bar" format="boolean"/>
        <!--是否需要底部播放进度条布局,一般在小视频全屏播放时不需要该布局,自己手工定制-->
        <attr name="is_need_play_progress_bar" format="boolean"/>
        <!--是否是全屏显示模式-->
        <attr name="is_fullscreen" format="boolean"/>
    </declare-styleable>
</resources>

java代码中初始化相关的代码并获取attr值

public VideoItemView(Context context) {
        this(context, null);
    }

    public VideoItemView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public VideoItemView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        if (IS_DEBUG) {
            Log.i(TAG, "init()");
        }

        initViews(context, attrs);
    }

    private void initViews(Context context, AttributeSet attrs) {
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.VideoItemView);
        mIsNeedCoverLayout = ta.getBoolean(R.styleable.VideoItemView_is_need_cover_layout, false);
        mIsNeedTopBar = ta.getBoolean(R.styleable.VideoItemView_is_need_top_bar, false);
        mIsNeedDefaultProgressBar = ta.getBoolean(R.styleable.VideoItemView_is_need_default_progress_bar, false);
        mIsNeedPlayProgressBar = ta.getBoolean(R.styleable.VideoItemView_is_need_play_progress_bar, true);
        mIsFullscreen = ta.getBoolean(R.styleable.VideoItemView_is_fullscreen, false);
        mCoverLayoutPaddingLeft = (int) ta.getDimension(R.styleable.VideoItemView_cover_layout_padding_left, 0);
        mCoverLayoutPaddingRight = (int) ta.getDimension(R.styleable.VideoItemView_cover_layout_padding_right, 0);
        ta.recycle();
        mRootView = (RelativeLayout) View.inflate(context, R.layout.item_video_root_layout, this);

        if (mIsNeedCoverLayout) {
            initVideoCoverViews();
        } else {
            initAddPlayView();
        }
    }

猜你喜欢

转载自blog.csdn.net/u010838785/article/details/81740684