首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android R類資源索引詳解:R.styleable、R.drawable、R.id等區別與命名由來

     編輯:程式設計綜合問答

直接回答

R 代表 Resource(資源)的首字母。編譯過程中,`aapt`/`aapt2` 掃描 `res/` 目錄,為每個資源生成唯一整型 ID,存放在 `R.java` 靜態內部類中。

常見 R 子類對比

R.styleable 特殊性

`R.styleable` 不直接對應單個資源文件,而是為每個 `` 生成:

  • `R.styleable.MyView`:`int[]` 數組,包含該 styleable 下所有屬性的資源 ID
  • `R.styleable.MyView_attrName`:單個屬性的索引(在數組中的位置)
// attrs.xml

    
    


// 生成
R.styleable.CustomButton = new int[] { R.attr.cornerRadius, R.attr.borderColor };
R.styleable.CustomButton_cornerRadius = 0; // 數組索引
R.styleable.CustomButton_borderColor = 1;

// 自定義 View 解析
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomButton);
float radius = a.getDimension(R.styleable.CustomButton_cornerRadius, 0);
int color = a.getColor(R.styleable.CustomButton_borderColor, Color.BLACK);
a.recycle();

注意事項

  • R 類**最終編譯為 final 靜態常量**,運行時無反射開銷
  • **不要手動修改 R.java**,重新構建會覆蓋
  • 庫項目生成的 R 類非 final(AAR 支持),主項目合併時重新分配 ID
  • 資源名命名規範:小寫字母、數字、下劃線,不以數字開頭(如 `ic_launcher.xml`)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
子類資源目錄典型資源用途示例
R.drawableres/drawable/圖片、XML 繪圖、Shape、Selector`imageView.setImageResource(R.drawable.ic_launcher)`
R.layoutres/layout/界面布局 XML`setContentView(R.layout.activity_main)`
R.id布局中 `android:id`View 唯一標識`findViewById(R.id.btn_submit)`
R.stringres/values/strings.xml字符串、字符串數組`getString(R.string.app_name)`
R.colorres/values/colors.xml顏色值`ContextCompat.getColor(this, R.color.primary)`
R.dimenres/values/dimens.xml尺寸值`getResources().getDimension(R.dimen.margin)`
R.styleres/values/styles.xml樣式、主題``
R.styleableres/values/attrs.xml**自定義屬性** 索引數組自定義 View 解析 `attrs.xml` 中 ``
R.animres/anim/動畫 XML`AnimationUtils.loadAnimation(this, R.anim.fade_in)`
R.menures/menu/菜單 XML`menuInflater.inflate(R.menu.main_menu, menu)`
R.rawres/raw/原始文件(音頻、視頻、JSON)`InputStream is = getResources().openRawResource(R.raw.data)`
R.xmlres/xml/任意 XML 配置`XmlResourceParser xrp = getResources().getXml(R.xml.config)`