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.最后看布局文件中如何利用我们创建的自定义视图并设置其属性

"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" />

更多相关文章

  1. Android通过SOCKET下载文件的方法
  2. 00_JNI头文件
  3. Android 之 使用Pull 解析xml文件
  4. android : 控件在代码中设置属性-setWidth(int pixels)或setHeig
  5. android关于蓝牙不能传送APK文件
  6. Android布局文件-错误
  7. android 将资源文件复制到android系统中去 raw assert

随机推荐

  1. 函数式编程思维在三行代码情书中的应用
  2. 跨年游-四姑娘山大峰/二峰初级雪山攀登、
  3. 用 Vue 开发自己的 Chrome 扩展[每日前端
  4. 我还在生产玩 JDK7,JDK 15 却要来了!|新特
  5. 这才是GraphQL最详细的解释[每日前端夜话
  6. linux 破解root密码时遇到的问题
  7. SpringBoot热部署加持
  8. WebRTC 的现状和未来:专访 W3C WebRTC Cha
  9. Spring Boot Admin 2.0开箱体验
  10. 从一份配置清单详解Nginx服务器配置