安卓自定义控件--TypedArray 详解

    我本是在阅读TvRecyclerView的源码。我没有弄明白默认的选中图标到底如何设置的。我就去看源码,看到使用了TypeArray,于是记录下来,方便以后查看。

    使用流程如下:

    在attrs.xml中定义一个属性变量

 
 
<?xml version="1.0" encoding="utf-8" ?>
<resources>

      <declare-styleable name="TvRecyclerView">
        <attr name="scrollMode"/>
        <attr name="focusDrawable" format="reference" />
        <attr name="isAutoProcessFocus" format="boolean" />
        <attr name="focusScale" format="float" />
    </declare-styleable>

</resources>

在layout布局中

xmlns:app="http://schemas.android.com/apk/res-auto"
此句是声明自己的命名空间

app:focusDrawable="@drawable/default_focus"
focusDrawable是自定义的属性


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="#000000">

    <app.com.tvrecyclerview.TvRecyclerView
        android:id="@+id/tv_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="580dp"
        android:layout_centerInParent="true"
        android:layout_margin="20dp"
        app:focusDrawable="@drawable/default_focus"/>
</RelativeLayout>

在自定义控件中要用到在布局文件中定义的属性值获取方式如下

public TvRecyclerView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
    setAttributeSet(attrs);
    //省去一些代码
}


private void setAttributeSet(AttributeSet attrs) {
    if (attrs != null) {
        TypedArray typeArray = getContext().obtainStyledAttributes(attrs, R.styleable.TvRecyclerView);
        int type = typeArray.getInteger(R.styleable.TvRecyclerView_scrollMode, 0);
        if (type == 1) {
            mIsFollowScroll = true;
        }

        final Drawable drawable = typeArray.getDrawable(R.styleable.TvRecyclerView_focusDrawable);
        if (drawable != null) {
            setFocusDrawable(drawable);
        }

        mSelectedScaleValue = typeArray.getFloat(R.styleable.TvRecyclerView_focusScale, DEFAULT_SELECT_SCALE);
        mIsAutoProcessFocus = typeArray.getBoolean(R.styleable.TvRecyclerView_isAutoProcessFocus, true);
        if (!mIsAutoProcessFocus) {
            mSelectedScaleValue = 1.0f;
            setChildrenDrawingOrderEnabled(true);
        }
        typeArray.recycle();
    }
    if (mIsAutoProcessFocus) {
        // set TvRecyclerView process Focus
        setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
    }
}
            

猜你喜欢

转载自blog.csdn.net/qiaojianfang_1148/article/details/78741002