当前位置: 移动技术网 > 移动技术>移动开发>Android > Android自定义View详解

Android自定义View详解

2019年07月24日  | 移动技术网移动技术  | 我要评论
转载请标明出处: 很多的android入门程序猿来说对于android自定义view,可能都是比较恐惧的,但是这又是高手进阶的必经之路,所有准备在自定义view上面花一些

转载请标明出处:
很多的android入门程序猿来说对于android自定义view,可能都是比较恐惧的,但是这又是高手进阶的必经之路,所有准备在自定义view上面花一些功夫,多写一些文章。先总结下自定义view的步骤:
1、自定义view的属性
2、在view的构造方法中获得我们自定义的属性
[ 3、重写onmesure ]
4、重写ondraw
我把3用[]标出了,所以说3不一定是必须的,当然了大部分情况下还是需要重写的。
1、自定义view的属性,首先在res/values/  下建立一个attrs.xml , 在里面定义我们的属性和声明我们的整个样式。

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
 
 <attr name="titletext" format="string" /> 
 <attr name="titletextcolor" format="color" /> 
 <attr name="titletextsize" format="dimension" /> 
 
 <declare-styleable name="customtitleview"> 
  <attr name="titletext" /> 
  <attr name="titletextcolor" /> 
  <attr name="titletextsize" /> 
 </declare-styleable> 
 
</resources> 

我们定义了字体,字体颜色,字体大小3个属性,format是值该属性的取值类型:
一共有:string,color,demension,integer,enum,reference,float,boolean,fraction,flag;不清楚的可以google一把。
然后在布局中声明我们的自定义view

<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" 
 xmlns:tools="http://schemas.android.com/tools" 
 xmlns:custom="http://schemas.android.com/apk/res/com.example.customview01" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" > 
 
 <com.example.customview01.view.customtitleview 
  android:layout_width="200dp" 
  android:layout_height="100dp" 
  custom:titletext="3712" 
  custom:titletextcolor="#ff0000" 
  custom:titletextsize="40sp" /> 
 
</relativelayout> 

一定要引入 xmlns:custom="http://schemas.android.com/apk/res/com.example.customview01"我们的命名空间,后面的包路径指的是项目的package

2、在view的构造方法中,获得我们的自定义的样式

/** 
  * 文本 
  */ 
 private string mtitletext; 
 /** 
  * 文本的颜色 
  */ 
 private int mtitletextcolor; 
 /** 
  * 文本的大小 
  */ 
 private int mtitletextsize; 
 
 /** 
  * 绘制时控制文本绘制的范围 
  */ 
 private rect mbound; 
 private paint mpaint; 
 
 public customtitleview(context context, attributeset attrs) 
 { 
  this(context, attrs, 0); 
 } 
 
 public customtitleview(context context) 
 { 
  this(context, null); 
 } 
 
 /** 
  * 获得我自定义的样式属性 
  * 
  * @param context 
  * @param attrs 
  * @param defstyle 
  */ 
 public customtitleview(context context, attributeset attrs, int defstyle) 
 { 
  super(context, attrs, defstyle); 
  /** 
   * 获得我们所定义的自定义样式属性 
   */ 
  typedarray a = context.gettheme().obtainstyledattributes(attrs, r.styleable.customtitleview, defstyle, 0); 
  int n = a.getindexcount(); 
  for (int i = 0; i < n; i++) 
  { 
   int attr = a.getindex(i); 
   switch (attr) 
   { 
   case r.styleable.customtitleview_titletext: 
    mtitletext = a.getstring(attr); 
    break; 
   case r.styleable.customtitleview_titletextcolor: 
    // 默认颜色设置为黑色 
    mtitletextcolor = a.getcolor(attr, color.black); 
    break; 
   case r.styleable.customtitleview_titletextsize: 
    // 默认设置为16sp,typevalue也可以把sp转化为px 
    mtitletextsize = a.getdimensionpixelsize(attr, (int) typedvalue.applydimension( 
      typedvalue.complex_unit_sp, 16, getresources().getdisplaymetrics())); 
    break; 
 
   } 
 
  } 
  a.recycle(); 
 
  /** 
   * 获得绘制文本的宽和高 
   */ 
  mpaint = new paint(); 
  mpaint.settextsize(mtitletextsize); 
  // mpaint.setcolor(mtitletextcolor); 
  mbound = new rect(); 
  mpaint.gettextbounds(mtitletext, 0, mtitletext.length(), mbound); 
 
 } 

我们重写了3个构造方法,默认的布局文件调用的是两个参数的构造方法,所以记得让所有的构造调用我们的三个参数的构造,我们在三个参数的构造中获得自定义属性。
3、我们重写ondraw,onmesure调用系统提供的:

@override 
 protected void onmeasure(int widthmeasurespec, int heightmeasurespec) 
 { 
  super.onmeasure(widthmeasurespec, heightmeasurespec); 
 } 
 
 @override 
 protected void ondraw(canvas canvas) 
 { 
  mpaint.setcolor(color.yellow); 
  canvas.drawrect(0, 0, getmeasuredwidth(), getmeasuredheight(), mpaint); 
 
  mpaint.setcolor(mtitletextcolor); 
  canvas.drawtext(mtitletext, getwidth() / 2 - mbound.width() / 2, getheight() / 2 + mbound.height() / 2, mpaint); 
 } 

此时的效果是:

是不是觉得还不错,基本已经实现了自定义view。但是此时如果我们把布局文件的宽和高写成wrap_content,会发现效果并不是我们的预期:


系统帮我们测量的高度和宽度都是match_parnet,当我们设置明确的宽度和高度时,系统帮我们测量的结果就是我们设置的结果,当我们设置为wrap_content,或者match_parent系统帮我们测量的结果就是match_parent的长度。
所以,当设置了wrap_content时,我们需要自己进行测量,即重写onmesure方法”:
重写之前先了解measurespec的specmode,一共三种类型:
exactly:一般是设置了明确的值或者是match_parent
at_most:表示子布局限制在一个最大值内,一般为warp_content
unspecified:表示子布局想要多大就多大,很少使用
下面是我们重写onmeasure代码:

@override 
protected void onmeasure(int widthmeasurespec, int heightmeasurespec) 
{ 
 int widthmode = measurespec.getmode(widthmeasurespec); 
 int widthsize = measurespec.getsize(widthmeasurespec); 
 int heightmode = measurespec.getmode(heightmeasurespec); 
 int heightsize = measurespec.getsize(heightmeasurespec); 
 int width; 
 int height ; 
 if (widthmode == measurespec.exactly) 
 { 
  width = widthsize; 
 } else 
 { 
  mpaint.settextsize(mtitletextsize); 
  mpaint.gettextbounds(mtitle, 0, mtitle.length(), mbounds); 
  float textwidth = mbounds.width(); 
  int desired = (int) (getpaddingleft() + textwidth + getpaddingright()); 
  width = desired; 
 } 
 
 if (heightmode == measurespec.exactly) 
 { 
  height = heightsize; 
 } else 
 { 
  mpaint.settextsize(mtitletextsize); 
  mpaint.gettextbounds(mtitle, 0, mtitle.length(), mbounds); 
  float textheight = mbounds.height(); 
  int desired = (int) (getpaddingtop() + textheight + getpaddingbottom()); 
  height = desired; 
 } 
  
  
 
 setmeasureddimension(width, height); 
} 

现在我们修改下布局文件:

<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" 
 xmlns:tools="http://schemas.android.com/tools" 
 xmlns:custom="http://schemas.android.com/apk/res/com.example.customview01" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" > 
 
 <com.example.customview01.view.customtitleview 
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content" 
  custom:titletext="3712" 
  android:padding="10dp" 
  custom:titletextcolor="#ff0000" 
  android:layout_centerinparent="true" 
  custom:titletextsize="40sp" /> 
 
</relativelayout> 

现在的效果是:


完全复合我们的预期,现在我们可以对高度、宽度进行随便的设置了,基本可以满足我们的需求。
当然了,这样下来我们这个自定义view与textview相比岂不是没什么优势,所有我们觉得给自定义view添加一个事件:
在构造中添加:

this.setonclicklistener(new onclicklistener() 
  { 
 
   @override 
   public void onclick(view v) 
   { 
    mtitletext = randomtext(); 
    postinvalidate(); 
   } 
 
  }); 
private string randomtext() 
 { 
  random random = new random(); 
  set<integer> set = new hashset<integer>(); 
  while (set.size() < 4) 
  { 
   int randomint = random.nextint(10); 
   set.add(randomint); 
  } 
  stringbuffer sb = new stringbuffer(); 
  for (integer i : set) 
  { 
   sb.append("" + i); 
  } 
 
  return sb.tostring(); 
 } 

下面再来运行:


我们添加了一个点击事件,每次让它随机生成一个4位的随机数,有兴趣的可以在ondraw中添加一点噪点,然后改写为验证码,是不是感觉很不错。

源码下载:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网