【Android】TypedArray的使用

介绍

看电池电量组件BatteryMeterView的时候看到的。

Array是个数组,所有TypedArray也是个容器,基本是用于自定义View里面的(至少我目前见过的全部都在自定义View里面)。

使用

1.自定义View

html 复制代码
public class RoundSeekbarView extends View {
    public RoundSeekbarView(Context context) {
        super(context);
    }

    public RoundSeekbarView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }
}

2.添加资源

在res/valus/attrs中添加资源,没有attrs文件就创建一个。使用declare-styleable,这里有一点要注意,那就是name一定要跟自定义的View的类名一致,例如我在第一步自定义的View的类名是RoundSeekbarView,这里的declare-styleable的name也一定要是RoundSeekbarView。

html 复制代码
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="RoundSeekbarView">
        <attr name="frameColor" format="color"/>
        <attr name="textAppearance" format="reference"/>
    </declare-styleable>
</resources>

format是这个属性的类型,有以下类型:

|-----------|---------|
| reference | 引用某一资源值 |
| string | 字符串 |
| color | 颜色 |
| dimension | 尺寸 |
| boolean | 布尔值 |
| integer | int整数类型 |
| float | 浮点数 |
| fraction | 百分数 |
| enum | 枚举 |
| flag | 位运算 |

3.在布局文件中使用自定义的View

html 复制代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".CanvasActivity">
    <com.example.sim.view.RoundSeekbarView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:frameColor="#908899ff"/>
</LinearLayout>

这里的app:xxx取决于你在第二部给这个属性起的名字,如果你起的是barColor,那么当你在布局文件中给RoundSeekbarView添加属性时就会弹出barColor的提示,这就是declare-styleable的name也一定要是RoundSeekbarView的意义。

4.TypedArray的使用

上面三步都是使用TypedArray的准备工作,接下来就到了TypedArray的使用了。

它是这样子用的,首先通过context.obtainStyledAttributes方法获取TypedArray实例

java 复制代码
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundSeekbarView);

然后通过对应的get方法获取资源,例如获取format是颜色的资源使用getColor

java 复制代码
int frameColor = typedArray.getColor(R.styleable.RoundSeekbarView_frameColor, Color.BLUE);

获取资源的使用getResourceId

java 复制代码
int textAppearance=typedArray.getResourceId(R.styleable.RoundSeekbarView_textAppearance,0);

其他的资源也有对应的get方法

注意,获取完资源之后要使用

java 复制代码
typedArray.recycle();

回收typedArray资源。

相关推荐
韩仔搭建4 小时前
第二章:安卓端启动流程详解与疑难杂症调试手册
android·ui·娱乐
A-花开堪折4 小时前
Android7 Input(七)App与input系统服务建立连接
android
冰糖葫芦三剑客4 小时前
Android 自定义悬浮拖动吸附按钮
android
吃汉堡吃到饱4 小时前
【Android】从Choreographer到UI渲染(二)
android·ui
微信公众号:AI创造财富5 小时前
显示的图标跟UI界面对应不上。
android·ui
aningxiaoxixi5 小时前
安卓 Audio Stream 类型
android
奔跑吧 android5 小时前
【android bluetooth 协议分析 01】【HCI 层介绍 3】【NUMBER_OF_COMPLETED_PACKETS 事件介绍】
android·bluetooth·hci·bt·gd·aosp13
_龙小鱼_7 小时前
Kotlin扩展简化Android动画开发
android·开发语言·kotlin
奔跑吧 android8 小时前
【android bluetooth 协议分析 01】【HCI 层介绍 6】【WriteLeHostSupport命令介绍】
android·bluetooth·bt·gd·aosp13·writelehostsup·hcicmd
uwvwko8 小时前
ctfshow——web入门254~258
android·前端·web·ctf·反序列化