安卓自定义property值
时间: 2023-09-10 12:15:47 浏览: 51
在 Android 中,我们可以使用自定义属性(Custom Attributes)来扩展现有的属性集,以满足我们的定制需求。自定义属性可以在 XML 文件中定义,然后在 Java 代码中使用。
以下是一个自定义属性的示例:
在 res/values/attrs.xml 文件中添加以下代码:
```
<resources>
<declare-styleable name="MyCustomView">
<attr name="customAttr" format="string" />
</declare-styleable>
</resources>
```
这个声明了一个名为 MyCustomView 的属性集合,其中包含一个名为 customAttr 的属性,其格式为字符串。
在布局文件中使用:
```
<com.example.MyCustomView
android:layout_width="match_parent"
android:layout_height="wrap_content"
customAttr="myCustomValue" />
```
在 Java 代码中使用:
```
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView);
String customValue = a.getString(R.styleable.MyCustomView_customAttr);
a.recycle();
```
这里我们使用 `obtainStyledAttributes` 方法获取自定义属性的值,然后使用 `recycle` 方法释放 TypedArray 对象。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)