android中定义了很多view与viewgroup,开发简单的程序一般够用了,但有时候我们要做一些复杂的界面或者特殊功能,这时候就需要自己定义view。
1、新建view类
public class HelloView extends View{
public HelloView(Context context){
super(context);
}
public HelloView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SubjectSelectorView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
}
view类有三个构造函数,一般定义第二个就可以了,可以接受从xml中传递的参数,否则在xml中使用的时候会出错。
2、自绘view
为HelloView添加OnDraw函数
自绘view主要用的下面几个类:
画笔 Paint
画布 Canvas
位图 Bitmap
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStyle(Style.FILL);
canvas.drawRect(0, 0, 100, 100, paint);
paint.setColor(Color.RED);
paint.setTextAlign(Align.LEFT);
canvas.drawText("蓝底红字", 50, 50, paint);
super.onDraw(canvas);
}
3、调用view,直接调用或在xml中添加自定义view
直接在代码中调用,直接设置该view为contentview:
SetContentView(new HelloView(this));
在xml中调用,该方法就要求view中必须有第二个构造函数:
<test.view.HelloView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
4、Bitmap相关的一些方法
使用BitmapFactory解析图片:
InputStream in = getResources().openRawResource(R.drawable.haha);
Bitmap bitmap = BitmapFactory.decodeStream(in);
使用BitmapDrawable解析图片:
BitmapDrawable bitmapDrawable = (BitmapDrawable) getResources().getDrawable(R.drawable.haha);
Bitmap bitmap = bitmapDrawable.getBitmap();
使用InputStream和BitmapDrawable解析:
InputStream in = getResources().openRawResource(R.drawable.haha);
BitmapDrawable bitmapDrawable = new BitmapDrawable(in);
Bitmap bitmap = bitmapDrawable.getBitmap();
使用BitmapFactory.Option解析图片--据说这样最省内存,貌似就是把图片解析成指定的格式了:
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inPurgeable = true;
opt.inInputShareable = true;
InputStream is = context.getResources().openRawResource(R.drawable.haha);
Bitmap bitmap = BitmapFactory.decodeStream(is,null,opt);
5、自定义view的某些属性
这个暂时就不研究了,用到的可能性很小的。