• typearray和obtainStyledAttribute的作用


    通常是在资源文件下创建attrs.xml

    1.attrs.xml

    <?xml version="1.0" encoding="utf-8"?>   
    <resources>   
        <declare-styleable name="button">   
            <attr name="textSize" format="dimension" />   
        </declare-styleable>   
    </resources>
    根标签要是resources,定义的变量要有个名字,declare-styleable name="button">,这里定义名称为button。在这个名称里,可以有多个自定义属性。定义了个名为textSize的属性,格式是dimension,这个format指定了textSize属性的类型,只能用于定义字体大小。

    2.布局文件如下:

    <?xml version="1.0" encoding="utf-8"?> 
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
        xmlns:myapp="http://schemas.android.com/apk/res/com.easymorse.textbutton" 
        android:orientation="vertical" android:layout_width="fill_parent" 
        android:layout_height="fill_parent" android:background="@drawable/background_color"> 
        <LinearLayout android:layout_width="fill_parent" 
            android:layout_height="10dip" /> 
        <LinearLayout android:layout_width="fill_parent" 
            android:layout_height="40dip"> 
            <com.easymorse.textbutton.TextButton 
                android:layout_width="fill_parent" android:layout_height="fill_parent" 
                android:layout_weight="1" android:text="电影" 
                android:gravity="center_vertical|center_horizontal" 
                android:background="@drawable/button" android:focusable="true" 
                android:clickable="true" myapp:textSize="20sp" />
    
    根标签中多了一个 xmlns:myapp
    myapp:textSize="20sp"

    3.在程序下获取该值

    public TextButton(final Context context, AttributeSet attrs) { 
        this(context, attrs, 0); 
        TypedArray typedArray=context.obtainStyledAttributes(attrs, R.styleable.button); 
        this.setTextSize(typedArray.getDimension(R.styleable.button_textSize, 15)); 
        typedArray.recycle();
    
      TypedArray 和obtainStyledAttributes(AttributeSet attrs,R.styleable.button)

    4.

    这里的自定义属性的format,可以有很多种:
    
    reference
    string
    color
    dimension
    boolean
    integer
    float
    fraction
    enum
    flag
  • 相关阅读:
    MySQL-EXPLAIN执行计划字段解释
    MySQL-EXPLAIN执行计划Extra解释
    HTTP与HTTPS的区别
    【面试】Java中sleep和wait的区别
    Nginx之前后端分离(入门)
    玩程序 之 一 . 字符串处理工具(可通过C#脚本扩展)
    C#实现下载功能,可用于软件自动更新
    对c#剪切板Clipboard占用的问题一点解决方法
    C# 制作 仪表
    C#使用自定义字体(从文件获取)
  • 原文地址:https://www.cnblogs.com/zhengtu2015/p/5018582.html
Copyright © 2020-2023  润新知