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>
  • 相关阅读:
    树的递归
    《计算机存储与外设》 3二级存储器
    《计算机存储与外设》 2主存储器
    《码农翻身:用故事给技术加点料》阅读有感
    分析"傍富婆发财"
    《第22条军规》Catch-22
    《编译原理》4
    《编译原理》3
    《血酬定律》
    linux下netcore程序部署
  • 原文地址:https://www.cnblogs.com/suiyilaile/p/9020143.html
Copyright © 2011-2022 走看看