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

本文介绍了TvRecyclerView中设置默认选中图标的方法。通过在attrs.xml定义属性,并在layout布局中引用,最后在自定义控件中通过TypedArray获取属性值来实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    我本是在阅读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);
    }
}
            

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值