android自定义控件分为两类,一类是继承View,一类是继承ViewGroup。由于直接继承ViewGroup是在子View的基础上进行测量和定位的。自定义View大体上可以分类三类:
- 1.在现有控件的基础上进行拓展,可以修改UI显示及功能添加
- 2.创建组合控件,实现功能的服用
- 3.直接继承View实现全新的控件,可以定义UI显示及功能实现
- 首先来看一下自己定义的效果
public class CustomerRunLine extends View { private int mColor = 0; private int h = 0; private int w = 0; private Paint mPaint; private int space = 30; private int startX = 0; private int delayed = 5;
//以上都是我们自己定义view需要用的变量
public CustomerRunLine(Context context) { this(context, null);//注意这里是this,不是super } public CustomerRunLine(Context context, AttributeSet attrs) { this(context, attrs, 0);//注意这里是this,不是super } public CustomerRunLine(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr);//注意这里是super,不是this
//自定义的属性上场了,attrs.xml在下面了 TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.Customerview, 0, 0); h = mTypedArray.getDimensionPixelSize(R.styleable.Customerview_c_h, h); w = mTypedArray.getDimensionPixelSize(R.styleable.Customerview_c_w, w); mColor = mTypedArray.getColor(R.styleable.Customerview_c_color, mColor); mTypedArray.recycle();
mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setColor(mColor); mPaint.setStrokeWidth(w); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); float sw = this.getMeasuredWidth(); if (startX >= sw + (h + space) - (sw % (h + space))) { startX = 0; } else { startX += delayed; } //这是实现具体画线的啦float start = startX;while (start < sw) { canvas.drawLine(start, 5, start + h, 5, mPaint); start += (h + space); } start = startX - h - space; while (start >= -h) { canvas.drawLine(start, 5, start + h, 5, mPaint); start -= (h + space); } invalidate();//这里是实现连续调用,否则只调用一下 }}
attrs.xml内容
<declare-styleable name="Customerview"> <attr name="c_h" format="dimension"></attr> <attr name="c_w" format="dimension"></attr> <attr name="c_color" format="color"></attr></declare-styleable>
然后我们就可以在
activity_main.xml布局中调用了,怎么看贴代码

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <test.com.test.CustomerRunLine android:layout_width="match_parent" android:layout_height="10dp" android:paddingBottom="50dp" app:c_color="#ef5621" app:c_h="80dp" app:c_w="4dp" /> </LinearLayout>其中这三个值代表我们自定义控件的属性啦,就是滚动条的颜色,宽度,高度,这里命名不好了,将就着看吧

app:c_color="#ef5621" app:c_h="80dp" app:c_w="4dp"
最后我们在看看activity的代码很简单啦
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }好了,到目前为止你就可以看到,刚开始的效果啦。

github地址:https://github.com/xiangtongcheng/customerView