寻梦者 发表于 2013-1-28 19:04:53

自定义View的注意点

最近在家无事,开始学习android。
自己做了一个自定义的View,布署到main.xml上去,却发现跑的时候老是出现错误。
后来发现,原来是集成View的时候没有写上父类3个参数的构造方法。
估计其内部默认情况下会调用那个构造方法吧。
 
 
贴上代码:
main.xml
<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent" android:layout_height="fill_parent"><com.ant.memory.PhotoViewandroid:id="@+id/photo" android:layout_width="fill_parent"android:background="#0000ff"android:layout_height="fill_parent" tileSize="24" /></FrameLayout> 
PhotoView:
public class PhotoView extends View {/* * 这个constructor是必须的要的,如果你想将这个View布署道main.xml上 */public PhotoView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);}@Overridepublic void draw(Canvas canvas) {// TODO Auto-generated method stubsuper.draw(canvas);InputStream is=getResources().openRawResource(R.drawable.back);Bitmap bitmap=BitmapFactory.decodeStream(is);Paint paint=new Paint();canvas.drawBitmap(bitmap, 50, 50, paint);}} 
 
Memory.java:
package com.ant.memory;import android.app.Activity;import android.os.Bundle;import android.view.Window;public class Memory extends Activity {    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {      super.onCreate(savedInstanceState);      requestWindowFeature(Window.FEATURE_NO_TITLE);      PhotoView photoView;      setContentView(R.layout.main);      photoView=(PhotoView) findViewById(R.id.photo);    }} 
页: [1]
查看完整版本: 自定义View的注意点