2015/9/8-4

Android自定义控件

我们每天的开发工作当中都在不停地跟View打交道,Android中的任何一个布局、任何一个控件其实都是直接或间接继承自View的,如TextView、Button、ImageView、ListView等。这些控件虽然是Android系统本身就提供好的,我们只需要拿过来使用就可以了,但你知道它们是怎样被绘制到屏幕上的吗?

速成班

先简单的画一个图

  • 首先要继承View
  • 实现他的几个方法(ps.可以不做任何动作)
  • 实现onDraw方法就可以开始画了
  • onDraw里面提供了一个参数Canvas,这是一块画布。然后我们要自己创建一只画笔Paint
  • 然后用paint+Canvas绘制出各种东西。(ps。canvas。Draw绘制时要填入的参数代表距离父控件的距离)

-

package com.zsz.develop.sidebardemo;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by shengzhong on 2015/9/8.
 */
public class customView extends View {

private Paint mPaint=new Paint();

public customView(Context context) {
    super(context);
}

public customView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public customView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

@Override
protected void onDraw(Canvas canvas) {
    mPaint.setColor(Color.RED);
    canvas.drawRect(0, 0, 300, 400, mPaint);
    mPaint.setColor(Color.BLACK);
    mPaint.setTextSize(20);
    String text ="hello";
    canvas.drawText(text,0,getHeight()/2,mPaint);

}
}

绘制sideBar,通讯录边上右一栏的绘制

通过for循环绘制每个字母。选中和没选中的颜色也是不一样的。最后还要重置画笔。

/**
 * 重写这个方法
 */
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    // 获取焦点改变背景颜色.
    int height = getHeight();// 获取对应高度
    int width = getWidth(); // 获取对应宽度
    int singleHeight = height / b.length;// 获取每一个字母的高度

    for (int i = 0; i < b.length; i++) {
        paint.setColor(Color.rgb(33, 65, 98));
        // paint.setColor(Color.WHITE);
        paint.setTypeface(Typeface.DEFAULT_BOLD);
        paint.setAntiAlias(true);
        paint.setTextSize(20);
        // 选中的状态
        if (i == choose) {
            paint.setColor(Color.parseColor("#3399ff"));
            paint.setFakeBoldText(true);
        }
        // x坐标等于中间-字符串宽度的一半.
        float xPos = width / 2 - paint.measureText(b[i]) / 2;
        float yPos = singleHeight * i + singleHeight;
        canvas.drawText(b[i], xPos, yPos, paint);
        paint.reset();// 重置画笔
    }

}