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,自定义,视图,属性
0
投稿

猜你喜欢

  • 那些年,我还在学习C# 学习笔记

    2021-11-09 07:08:35
  • Android用PopupWindow实现自定义overflow

    2021-08-08 22:56:06
  • 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
  • Java中对象的销毁方法分析

    2023-01-09 16:44:29
  • IDEA的默认快捷键设置与Eclipse的常用快捷键的设置方法

    2023-04-09 18:32:40
  • SpringBoot结合Redis配置工具类实现动态切换库

    2022-04-15 14:14:13
  • 深入解析Java的Spring框架中bean的依赖注入

    2023-12-20 18:50:52
  • Java程序打包成带参数的jar文件实例代码

    2022-12-12 03:50:39
  • Java内存模型final的内存语义

    2023-06-05 08:02:25
  • java equals函数用法详解

    2022-07-31 06:40:20
  • 七个Spring核心模块详解

    2021-07-25 15:32:18
  • SpringBoot项目@Async方法问题解决方案

    2023-11-12 03:55:26
  • C#实现单词本功能

    2021-11-06 13:08:23
  • 详解Spark Sql在UDF中如何引用外部数据

    2021-08-17 14:51:17
  • Java流程控制break和continue

    2023-06-16 09:49:54
  • java中Class.forName方法的作用详解

    2021-07-08 21:47:31
  • asp之家 软件编程 m.aspxhome.com