Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
599 views
in Technique[技术] by (71.8m points)

android - Custom SurfaceView causing NoSuchMethodException

I have a custom View extending SurfaceView. The XML layout is

<com.myPackage.MyCustomView
  android:id="@+id/mycview"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"/>

The class is :

public class MyCustomView extends SurfaceView{

public float[] xpositions;
public float[] ypositions;
public String[] units;


public MyCustomView(Context context, float[] xpos, float[] ypos,String[] u) {
    super(context);
    xpositions=xpos;
    ypositions =ypos;
    units=u;


     }
}

In the context Activity for this method, I have the following line

MyCustomView mv = (MyCustomView)findViewById(R.id.mycview);

The Logcat output has the following

01-30 01:51:12.124: ERROR/AndroidRuntime(4934): Caused by:  java.lang.NoSuchMethodException:MyCustomView(Context,AttributeSet) 
01-30 01:51:12.124: ERROR/AndroidRuntime(4934):    at java.lang.Class.getMatchingConstructor(Class.java:674) 
01-30 01:51:12.124: ERROR/AndroidRuntime(4934):     at java.lang.Class.getConstructor(Class.java:486) 
01-30 01:51:12.124: ERROR/AndroidRuntime(4934):     at android.view.LayoutInflater.createView(LayoutInflater.java:475)

For some reason, my constructor is causing above exception. I would appreciate any help finding what is wrong with the code.

UPDATE: I changed the constructor to add AttributeSet and in my activity wrote the following:

 XmlPullParser parser = getResources().getXml(R.id.mycview);
 AttributeSet attributes = Xml.asAttributeSet(parser);


 MyCustomView cv = new MyCustomView(this,attributes,xx,yy,uu);
              cv = (MyCustomView)findViewById(R.id.mycview);

But I get the same logcat output.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You don't have the correct constructor MyCustomView(Context,AttributeSet)

You must create the following constructors if you want to inflate views, and create new one in code. use initYourStuff() to init your stuff ;) , you can also parametrize them of course...

public MyCustomView(Context context)
{
    super(context);
    this.context = context;
    initYourStuff();

}

public MyCustomView(Context context, AttributeSet attrs)
{
    super(context, attrs);
    this.context = context;
    initYourStuff();
}

public MyCustomView(Context context, AttributeSet attrs, int defStyle)
{
    super(context, attrs, defStyle);
    this.context = context;
    initYourStuff();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...