牙叔教程 簡單易懂
這裡我們先舉個例子
在安卓中, 使用顔色是這樣的: 在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了
環境設備: 小米11proAndroid版本: 12雷電模拟器:9.0.17Android版本: 9Autojs版本: 9.2.13
名人名言思路是最重要的, 其他的百度, bing, stackoverflow, github, 安卓文檔, autojs文檔, 最後才是群裡問問 --- 牙叔教程
聲明部分内容來自網絡 本教程僅用于學習, 禁止用于其他用途
,更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!