• 自定义控件:自定义属性


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

    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>
  • 相关阅读:
    Appium安装教程
    方法(method)和函数(function)有什么区别?
    FTP两种工作模式:主动模式(Active FTP)和被动模式介绍
    python socket编程介绍
    面向对象基础篇
    python fishc.homework2
    python遇到的问题汇总
    我对 python 面向对象的理解
    深入理解JVM(五)JVM优化策略
    深入理解JVM(四)JVM性能监控与故障处理工具
  • 原文地址:https://www.cnblogs.com/suiyilaile/p/9020143.html
Copyright © 2020-2023  润新知