android - 自定义 SurfaceView 导致 NoSuchMethodException

标签 android xml exception constructor custom-view

我有一个扩展 SurfaceView 的自定义 View 。 XML 布局是

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

类是:

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;


     }
}

在此方法的上下文 Activity 中,我有以下行

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

Logcat 输出有以下内容

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)

出于某种原因,我的构造函数导致了上述异常。如果能帮助我找出代码中的问题,我将不胜感激。

更新: 我更改了构造函数以添加 AttributeSet 并在我的 Activity 中编写了以下内容:

 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);

但我得到了相同的 logcat 输出。

最佳答案

您没有正确的构造函数 MyCustomView(Context,AttributeSet)

如果您想膨胀 View ,您必须创建以下构造函数,并在代码中创建新的构造函数。 使用 initYourStuff() 来初始化你的东西 ;),你当然也可以参数化它们......

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();
}

关于android - 自定义 SurfaceView 导致 NoSuchMethodException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9054894/

相关文章:

java - 第二次解析 XML 文件时出现 XStream ConversionException

c# - OperationCanceledException 和 TaskCanceledException 之间的区别?

windows-phone-7 - 缺少 ApplicationException 基类?

java - Android 应用请求 Firebase 自定义身份验证

android - 将 Unity 应用程序添加到新的结构组织、现有的 firebase 项目

android - 在android应用程序中存储多个用户数据的最佳方式

java - Android:资源中的翻译

.net - 当 ADO.NET 查询无法检索请求的数据时应抛出什么异常?

android - 将 ViewPager fragment 化为 Play 商店应用程序?

java - 找不到以下类: com. codecarpet.fbconnect.FBLoginButton