【问题标题】:Custom SurfaceView causing NoSuchMethodException自定义 SurfaceView 导致 NoSuchMethodException
【发布时间】:2026-02-18 19:35:01
【问题描述】:

我有一个扩展 SurfaceView 的自定义视图。 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 并在我的活动中写了以下内容:

 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 输出。

【问题讨论】:

    标签: android xml exception constructor custom-view


    【解决方案1】:

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

    如果你想膨胀视图,你必须创建以下构造函数,并在代码中创建一个新的。 使用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();
    }
    

    【讨论】:

    • 感谢您的回复。我按照你说的做了,看我的更新。我仍然遇到同样的异常
    • 尝试静态内部类。
    最近更新 更多