zoukankan      html  css  js  c++  java
  • 自定义控件:自定义属性

    在做自定义控件时,我们想给控件自定义某些属性时,可以通过以下方法解决。

    1.在values文件夹下,新建attr.xml文件

    1 <?xml version="1.0" encoding="utf-8"?>
    2 <resources>
    3     <declare-styleable name="MyFirstCustomView">
    4         <attr name="customColor" format="color"></attr>
    5         <attr name="customTextSize" format="dimension"></attr>
    6     </declare-styleable>
    7 </resources>
    declare-styleable 定义了一个属性节点,attr代表自定义属性名称,format代表属性值类型

    2.创建自定义控件MyFirstCustomerView
     1 public class MyFirstCustomView extends TextView {
     2 
     3     public MyFirstCustomView(Context context) {
     4         this(context,null);
     5     }
     6 
     7     public MyFirstCustomView(Context context, AttributeSet attrs) {
     8         this(context,attrs,0);
     9     }
    10 
    11     public MyFirstCustomView(Context context, AttributeSet attrs, int defStyle) {
    12         super(context, attrs, defStyle);
    13         TypedArray _typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyFirstCustomView,0,0);
    14         int color = _typedArray.getColor(R.styleable.MyFirstCustomView_customColor,0);
    15         float size = _typedArray.getDimension(R.styleable.MyFirstCustomView_customTextSize,24);
    16         setTextColor(color);
    17         setTextSize(size);
    18         _typedArray.recycle();
    19     }
    20 
    21 }
     TypedArray 数组容器,通过它获取自定义的属性值:
    _typedArray.getColor(R.styleable.MyFirstCustomView_customColor,0);//获取自定义的值customColor
    _typedArray.getColor(R.styleable.MyFirstCustomView_customTextSize,24);//获取自定义的值customTextSize,默认24
    _typedArray用完后需要recycle()回收。

    3.在layout布局文件中引用控件
     1 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
     2     xmlns:tools="http://schemas.android.com/tools"
     3     android:layout_width="match_parent"
     4     android:layout_height="match_parent"
     5     xmlns:app="http://schemas.android.com/apk/res-auto"
     6     tools:context="com.zc.myapp.fragment.HomeFragment">
     7 
     8     <com.zc.baselib.view.MyFirstCustomView
     9         android:layout_width="match_parent"
    10         android:layout_height="wrap_content"
    11         android:layout_marginTop="@dimen/margin_msg"
    12         android:text="自定义控件(首页)"
    13         app:customColor="@color/color_theme"
    14         app:customTextSize="@dimen/middle_txt_size"/>
    15 
    16 </FrameLayout>
  • 相关阅读:
    Mac下Intellij IDEA Console中文是?
    MAC && Linux terminal session clone
    高扩展性网站的原则
    职场感悟
    如何保持自己 fork 的项目和原始项目同步
    统一回复一下同学们的咨询
    Can't exec "aclocal": No such file or directory at /usr/share/autoconf/Autom4te/FileUtils.pm line 326.
    checking for tgetent()... configure: error: NOT FOUND!
    Simultaneous Tag Editing in IntelliJ IDEA 14.1
    Mac 配置 vim
  • 原文地址:https://www.cnblogs.com/suiyilaile/p/9020143.html
Copyright © 2011-2022 走看看