• androud 自定义属性


    在values文件夹下新建的attrs.xml文件如下:

    format是该属性的一种单位:有 color,String,references等。

    1 <?xml version="1.0" encoding="utf-8"?>
    2 <resources>
    3     <declare-styleable name="myCustomview">
    4         <attr name="android:text"/>
    5         <attr name="android:background"/>
    6         <attr name="text_color" format="color"/>
    7     </declare-styleable>
    8 
    9 </resources>

    这样声明有两种情况:

    1.有declare-styleable标签下,在java代码中直接就能通过TypeArray来获取属性对象

     TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.myCustomview);
    
            String text =  a.getString(R.styleable.myCustomview_android_text);

    2.表示定义下android系统自带的熟悉

    可以不需要 declare-styleable 但是在代码中获取属性就有点难

    在xml布局文件如下定义:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:whf="http://schemas.android.com/apk/com.example.wanghuafu.mymacandroid"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <com.example.wanghuafu.mymacandroid.MyCustomView
            android:layout_width="230dp"
            android:layout_height="79dp"
            android:id="@+id/mycustomview"
            whf:text="我是自定义属性,调用了"
            whf:text_color="@color/colorAccent"
            whf:background="@color/colorPrimary"
    
            />
    
    </LinearLayout>

    其中,xmlns:name是名字任意取,最后的命名空间要加上包名;

    如上可见,自定义属性也只是在定义view中使用,而不是在其他任意控件中使用

    <attr name="android:text"/>
  • 相关阅读:
    XML操作
    C# 相等(==,Equals)
    VS插件 选项卡竖排列
    springcloud版本号
    @EnableDiscoveryClient和@EnableEurekaClient的区别
    在mvn构建时直接将项目jar包做成服务第三方工具
    java引用的强制转型
    java基础类型的byte为长度
    springboot访问服务器本地静态文件的方法
    nginx反向代理和负载均衡的基本配置
  • 原文地址:https://www.cnblogs.com/taofudemo/p/5020890.html
Copyright © 2020-2023  润新知