Android 自定义View基本用法
看完鸿洋大神的自定义view一二三四, 写一下自己的总结:

一、自定义View的基本步骤:

  • 自定义属性:在res/values目录下创建attrs.xml
  • 自定义一个View:extends View, 获取自定义属性
  • 在布局文件中使用自定义的View

二、自定义属性:

       
         
        format="color"
/>
       
       
       

三、自定义一个View

首先在构造方法中获取刚才定义的一堆属性
      TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCircleView, defStyle, 0);
int n = a.getIndexCount();
for (int i = 0; i < n; i++)
{
int attr = a.getIndex(i);
switch (attr)
{
case R.styleable.MyCircleView_firstColor:
mFirstColor = a.getColor(attr, Color.GREEN);
break;
case R.styleable.MyCircleView_secondColor:
mSecondColor = a.getColor(attr, Color.RED);
break;
case R.styleable.MyCircleView_firstCircleWidth:
mFirstCircleWidth = a.getInt(attr, 20);
break;
case R.styleable.MyCircleView_secondCircleWidth:
mSecondCircleWidth = a.getInt(attr, 30);
break;
case R.styleable.MyCircleView_splitSize:
mSplitSize = a.getInt(attr, 40);
break;
}
}
a.recycle();
                mPaint = new Paint();
       然后重写onMeasure()方法,计算view的位置, 如果在布局文件中是match_parent或者给出了大小,就不需要重写,如果是wrap_content,则需要重写, 否则这个view会填充整个屏幕。如果重写了这个函数,则必须要setMeasureDimension(width, heigth), 将测量的width和height传到onDraw中使用。

            最后是onDraw()方法, 在给定的位置画View。在这里,我定义了两个圆,那么就是要计算两个圆的半径, 中心坐标都是getWidth()/2 , getHeight()/2, 两个在正中心的同心圆。
       关键的是半径:        第一个圆半径:getWidth()/2 - mFirstCircleWidth()/2;        第二个圆半径:getWidth()/2 - mFirstCircleWidth - mSplitSize - mSecondCircleWidth()/2;  

三、在xml中使用:

            xmlns:tools="http://schemas.android.com/tools"
    xmlns:test="http://schemas.android.com/apk/res/com.example.mycircleview"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
>
            android:layout_width="200dp"
        android:layout_height="200dp" 
android:layout_centerInParent="true" test:firstColor="#D4F668" test:secondColor="#2F9DD2" test:firstCircleWidth="20"                                 test:secondCircleWidth="30"                                 test:splitSize="30"  />                 










更多相关文章

  1. Android开发实践 Intent 解析
  2. android:shape妙用
  3. 【Android】TabLayout 自定义指示器 Indicator 样式
  4. Android(安卓)System Property
  5. Android各种信息的显示
  6. Android(安卓)SDK 22.0.1 引用 android-support-v4 的问题
  7. Android(安卓)manifest文件中的标签详细介绍
  8. android的充电图标显示
  9. Android中TabLayout切换选项背景和修改字体大小

随机推荐

  1. Android(安卓)EditText得到焦点失去焦点
  2. android中用socket 接收服务器的消息
  3. appcompat-v7 版本造成的问题No resource
  4. 2.20 android连接wifi,解决mWifiManager.a
  5. 向SD卡写文件
  6. Android(安卓)分多次(每次一个)请求权限时
  7. 怎么正确绘画人物头发?动漫头发上色画法
  8. xp一体机文件永久删除怎么找到
  9. VMware Workstation Linux 安装及桥接网
  10. 盲盒源码h5|数码盲盒源码开发搭建