zoukankan      html  css  js  c++  java
  • android 自定义属性

    1、定义属性名称、类型

    需要再res/values/attrs.xml 文件中配置

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <declare-styleable name="InputView">
            <attr name="buttonNum" format="integer"/>        
        </declare-styleable>
    </resources>

    2、在自定义控件的xml配置中使用自定义的属性

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:InputView="http://schemas.android.com/apk/res/com.example.sample" //自定义属性的命名控件,最后一段为项目的package名
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
    <com.self.InputView
          android:layout_width="120dp"
        android:layout_height="150dp"
        InputView:buttonNum="33"  // 通过自定义的命名控件使用自定义的属性
        />
    </LinearLayout>

    3、在自定义的控件的构造方法中获取自定义的属性值

    public class InputView extends EditText
    {
    
        public InputView(Context context, AttributeSet attrs)
        {
            super(context, attrs);   
       
            TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.InputView);
            int num = a.getInt(R.styleable.InputView_buttonNum, 0);
            Log.d("", "------------self attrs : "+num);
            a.recycle(); 
    
        }
    }

    4、其他属性类型:string , integer , dimension , reference , color , enum.

    前面几种的声明方式都是一致的,例如:<attr name="buttonNum" format="integer"/>。
    只有enum是不同的,用法举例:

    <attr name="testEnum">
        <enum name="fill_parent" value="-1"/>
        <enum name="wrap_content" value="-2"/>
    </attr> 

    还有另外一种简单做法,不许要使用xml配置属性名称、类型等,直接再attriable中获取属性值:

    1、再自定义控件的构造方法中获取

    resouceId = attrs.getAttributeResourceValue(null, "Text", 0);// 获取属性的资源id
    if (resouceId > 0) 
    { Text
    = context.getResources().getText(resouceId).toString();//根据id获取属性值 }

    2、在xml文件中使用自定义的属性值

    <com.EditText1 android:id="@+id/ss3"
            android:layout_width="wrap_content"     
            android:layout_height="wrap_content" Text="@string/app_name" />

    链接:

    http://www.cnblogs.com/ufocdy/archive/2011/05/27/2060221.html

    http://hi.baidu.com/jwq359699768/item/8dd1e663eadb4194c5d24928

  • 相关阅读:
    Postman请求Https接口与认证
    HTML实用
    ORM实例教程_转
    web跨域问题CORS
    gin入门
    swagger应用
    k8s之容器
    腾讯高级工程师:如何从头开始写游戏服务器框架_转
    tensorflow入门
    sublime Text 3实用功能和常用快捷键收集
  • 原文地址:https://www.cnblogs.com/lipeil/p/2725561.html
Copyright © 2011-2022 走看看