如何使用 android.R.attr. 引用属性
时间: 2023-12-05 20:03:26 浏览: 38
在 Android 中,我们可以使用 `android.R.attr` 来引用系统自带的属性。使用 `android.R.attr` 可以避免定义重复的属性,使得我们的代码更加简洁。
具体使用方法如下:
```
// 获取系统自带的 textColorPrimary 属性
int[] attrs = {android.R.attr.textColorPrimary};
TypedArray typedArray = context.obtainStyledAttributes(attrs);
int color = typedArray.getColor(0, Color.BLACK);
typedArray.recycle();
```
在上述代码中,我们使用 `android.R.attr.textColorPrimary` 引用了系统自带的属性,并通过 `context.obtainStyledAttributes()` 方法来获取该属性的值。
需要注意的是,使用 `android.R.attr` 引用属性时,需要将属性名前面的 `R.` 去掉。而且要记得在使用完 `TypedArray` 后调用 `recycle()` 方法以便及时回收内存。
相关问题
android r.style
引用\[1\]中提到了在layout文件中设置MyView的style属性为@style/RedStyle。这意味着我们可以在styles.xml文件中找到名为RedStyle的样式定义。同样地,我们可以在styles.xml文件中找到名为GreenStyle的样式定义,因为在引用\[3\]中提到了将myViewStyle赋值为@style/GreenStyle。所以,android中的r.style包含了RedStyle和GreenStyle这两个样式。
#### 引用[.reference_title]
- *1* *2* *3* [Android中View自定义XML属性详解以及R.attr与R.styleable的区别](https://blog.csdn.net/sunqunsunqun/article/details/50708044)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
如何在 java 文件中引用 listPreferredItemHeightSmall 属性
`listPreferredItemHeightSmall` 是系统自带的属性,如果要在 Java 文件中引用该属性,可以使用 `android.R.attr.listPreferredItemHeightSmall` 来引用。具体使用方法如下:
```
// 获取系统自带的 listPreferredItemHeightSmall 属性
int[] attrs = {android.R.attr.listPreferredItemHeightSmall};
TypedArray typedArray = context.obtainStyledAttributes(attrs);
int height = typedArray.getDimensionPixelSize(0, 0);
typedArray.recycle();
```
在上述代码中,我们使用 `android.R.attr.listPreferredItemHeightSmall` 引用了系统自带的属性,并通过 `context.obtainStyledAttributes()` 方法来获取该属性的值。
需要注意的是,这里获取到的是像素值,通过 `getDimensionPixelSize()` 方法获取。而且要记得在使用完 `TypedArray` 后调用 `recycle()` 方法以便及时回收内存。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)