autojs获取内置资源数字ID

665 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第1天,点击查看活动详情

牙叔教程 简单易懂

这里我们先举个例子

在安卓中, 使用颜色是这样的: 在xml文件中声明自定义color,使用时引入:

首先:在res/values文件夹下新建一个color.xml文件,在此文件中声明出自己想要使用的color

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="springgreen">#FF3CB371</color>
    <color name="silver">#FFC0C0C0</color>
    <color name="green">#FF056B05</color>
</resources>

然后:在你想要使用指定color的代码中引入,引入方法如下

ContextCompat.getColor(MyApplication.getContext(),R.color.springgreen)

\

在autojs怎么使用颜色呢?

首先你要知道autojs中有那些资源, 我们可以用mt管理器查看他的文件

resources.arsc

resources.arsc 是一个资源的索引表,里面维护者资源ID、Name、Path或者Value的对应关系,AssetManager通过这个索引表,就可以通过资源的ID找到这个资源对应的文件或者数据。

点击color目录下的color文件

\

会看到熟悉的十六进制颜色

比如这个颜色

<color name="accent_light">#35bcff</color>

\

我们现在去找他的id, 点击color下的type-info文件, 搜索accent_light

<entry id="0x7f060019" name="accent_light" />

用autojs获取一下这个颜色的id

/**
 * @description:
 * @param {string} resName
 * @param {string} resType
 * @return {*}
 */
function getResourceID(resName, resType) {
    var resource = context.getResources();
    return resource.getIdentifier(resName, resType, context.getPackageName());
}
let resId = getResourceID("accent_light", "color");
log(resId); // 2131099673

这个id是十进制, 我们转成十六进制

对比一下

<entry id="0x7f060019" name="accent_light" />

都是 7f060019;

id就得到了, 接下来, 通过id去获取对应的颜色

let resId = getResourceID("accent_light", "color");
log(resId);
// let value = context.getResources().getColor(resId, context.getTheme()); // -13255425
let value = context.getResources().getString(resId, context.getTheme());
log(value); // #ff35bcff

getColor获取的是颜色的十进制, getString获取的是十六进制, 都是同一个颜色

<color name="accent_light">#35bcff</color>

\

颜色就说完了, 我们再看看别的, 比如图片;

在res文件夹下有个图片

同样的, 我们去 resources.arsc 中搜索 4Q 这个名字

它在drawable下面

<path name="ic_usb_black_48dp">res/4Q.png</path>

通过名字获取资源id

let resId = getResourceID("ic_usb_black_48dp", "drawable");
log(resId); // 2131231860

\

通过id获取名字

let resId = getResourceID("ic_usb_black_48dp", "drawable");
log(resId); // 2131231860
let value = context.getResources().getString(resId, context.getTheme());
log(value); // res/4Q.png

名字显示出来的是文件路径

把这张图片放在ui中

"ui";
ui.layout(
    <vertical>
        <img id="img" w="100" h="100"></img>
    </vertical>
);

let resId = getResourceID("ic_usb_black_48dp", "drawable");
ui.img.setImageResource(resId);

\

字符串也是一样的, 找资源就去resources.arsc里面找

string/string

比如这个字符串

 <string name="xml_error">XML解析错误,相对控件不存在</string>

通过名字获取id, 设置文本控件内容

"ui";
ui.layout(
    <vertical>
        <text id="content" w="100" h="100" margin="30"></text>
    </vertical>
);

let resId = getResourceID("xml_error", "string");
ui.content.setText(resId);

换行是因为宽度从超过100dp了

环境

设备: 小米11pro
Android版本: 12
雷电模拟器:9.0.17
Android版本: 9
Autojs版本: 9.2.13

名人名言

思路是最重要的, 其他的百度, bing, stackoverflow, github, 安卓文档, autojs文档, 最后才是群里问问 --- 牙叔教程

声明

部分内容来自网络 本教程仅用于学习, 禁止用于其他用途

微信公众号 牙叔教程