美文网首页
Android自定义-attrs

Android自定义-attrs

作者: 就爱烫卷发 | 来源:发表于2019-06-09 23:08 被阅读0次

前言

       本想着趁着端午假期把自定义View好好总结一下的但是还是被耽误了,那就有时间就开始写吧,虽然是端午的尾巴,但是还是要总结一下的。
       前几天搞了个思维导图,觉得知识还是要成为结构,这样更容易理顺一点。所以简单的画了一下图,目前就先按照这个结构写,后期深入再补充吧。


结构.png

       Math是数学基础 ,要做自定义总要进行计算,我自己抄过来当表使。用到的时候自己查就行了。下面直奔主题,看自定义View的属性。
       我们写自定义View的时候都会进行一些属性的配置,首先在res->values中新建attrs资源文件夹定义View的名称以及View 所自己定义的属性:下面定义一个叫padding的参数,做我们常见的padding使用

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <declare-styleable name="AttrsView">
       <attr name="attrs_padding" format="dimension"/>
   </declare-styleable>
</resources>

name表示的是名称,format代表的是内容的形式,这里指尺寸值
具体内容如下:

属性表以及取值方法.png
上面几种的使用都是 <attr name="view_x" format="xxxx"/>而枚举和标志分别是
<attr enum="view_x" value="0"/> ------------枚举
<attr flag="view_x" value="1"/> ------------标志
以上概念介绍完毕之后就看实际用法了下面看
 public class AttrsView extends View {
    public AttrsView(Context context) {
       this(context,null);
      }
    public AttrsView(Context context,  AttributeSet attrs) {
      this(context, attrs,0);
      }
    public AttrsView(Context context,AttributeSet attrs, int defStyleAttr) {
      super(context, attrs, defStyleAttr);
      TypedArray typedArray =   context.obtainStyledAttributes(attrs,R.styleable.AttrsView);
      float view_padding  = typedArray.getDimension(
            R.styleable.AttrsView_attr_padding, dip2px(context, 50));
    //用完之后回收
      typedArray.recycle();
}

//dp转px
/**
 * Dip into pixels
 */
public static int dip2px(Context context, float dpValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (dpValue * scale + 0.5f);
}
  // px转dp
   /**
    * Pixels converted into a dip
    */
 public static int px2dip(Context context, float pxValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (pxValue / scale + 0.5f);
}
}

       自定义View要构造三个方法,在API21以上可以有四个构造方法,这里还写熟悉的三个,这里通过this一个调用一个 就不用在每一个里面都加上一个init()方法了。我们可以在这里初始化一些基本属性,比如画笔的颜色,控件的大小。

相关文章

网友评论

      本文标题:Android自定义-attrs

      本文链接:https://www.haomeiwen.com/subject/yahoxctx.html