Android如何自定义视图属性
作者:u011771755 时间:2021-11-23 04:27:39
本文实例为大家介绍了Android自定义视图属性的方法,供大家参考,具体内容如下
1. 自定义一个自己的视图类继承自View
public class MyView extends View
{
public MyView(Context context, AttributeSet attrs)
{
super(context, attrs);
//获取到自定义的属性
TypedArray ta=context.obtainStyledAttributes(attrs, R.styleable.MyView);
int color=ta.getColor(R.styleable.MyView_rect_color, 0xffff0000);
setBackgroundColor(color);
//必须手动回收ta
ta.recycle();
}
public MyView(Context context)
{
super(context);
}
}
2. 在res/values目录中新建一个attrs.xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
//定义一个declare-styleable标签,在里面设置attr属性
<declare-styleable name="MyView">
<attr name="rect_color" format="color"/>
</declare-styleable>
</resources>
一个attr属性,对应了一个视图属性
3.最后看布局文件中如何利用我们创建的自定义视图并设置其属性
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
//自定义一个MyView的命名空间
xmlns:gu="http://schemas.android.com/apk/res/com.gu.myrect"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.gu.myrect.MyView
android:layout_width="100dp"
android:layout_height="100dp"
//根据自定义的命名空间和我们在attrs中设置的属性,自定义属性值
gu:rect_color="#cc99cc" />
</LinearLayout>
标签:Android,自定义,视图,属性
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
那些年,我还在学习C# 学习笔记
2021-11-09 07:08:35
![](https://img.aspxhome.com/file/2023/8/92968_0s.jpg)
Android用PopupWindow实现自定义overflow
2021-08-08 22:56:06
![](https://img.aspxhome.com/file/2023/1/116001_0s.jpg)
Android非XML形式动态生成、调用页面的方法
2022-11-11 11:26:01
详解Java发送HTTP请求
2022-01-09 14:53:57
SpringBoot上传文件并配置本地资源映射来访问文件的实例代码
2023-07-24 02:41:08
c# socket编程udp客户端实现代码分享
2023-06-16 05:03:31
MyBatis-Plus多表联查(动态查询)的项目实践
2023-11-19 21:43:17
![](https://img.aspxhome.com/file/2023/3/59663_0s.png)
Java中对象的销毁方法分析
2023-01-09 16:44:29
IDEA的默认快捷键设置与Eclipse的常用快捷键的设置方法
2023-04-09 18:32:40
![](https://img.aspxhome.com/file/2023/7/78007_0s.png)
SpringBoot结合Redis配置工具类实现动态切换库
2022-04-15 14:14:13
深入解析Java的Spring框架中bean的依赖注入
2023-12-20 18:50:52
![](https://img.aspxhome.com/file/2023/8/66188_0s.png)
Java程序打包成带参数的jar文件实例代码
2022-12-12 03:50:39
Java内存模型final的内存语义
2023-06-05 08:02:25
![](https://img.aspxhome.com/file/2023/0/62130_0s.png)
java equals函数用法详解
2022-07-31 06:40:20
七个Spring核心模块详解
2021-07-25 15:32:18
SpringBoot项目@Async方法问题解决方案
2023-11-12 03:55:26
![](https://img.aspxhome.com/file/2023/2/58872_0s.png)
C#实现单词本功能
2021-11-06 13:08:23
![](https://img.aspxhome.com/file/2023/0/79080_0s.png)
详解Spark Sql在UDF中如何引用外部数据
2021-08-17 14:51:17
![](https://img.aspxhome.com/file/2023/4/64124_0s.jpg)
Java流程控制break和continue
2023-06-16 09:49:54
![](https://img.aspxhome.com/file/2023/6/85536_0s.png)
java中Class.forName方法的作用详解
2021-07-08 21:47:31