Could not find a method sendMessage(View) in the activity class

后端 未结 3 1430
野趣味
野趣味 2020-12-20 08:19

MainActivity.java

package com.example.myfirstapp;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Edi         


        
相关标签:
3条回答
  • 2020-12-20 08:55

    I was struggling with a similar error following the android tutorial

    E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.myfirstapp, PID: 18300
                  java.lang.IllegalStateException: Could not find method sendMessage (MainActivity)(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'button'
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
                      at android.view.View.performClick(View.java:5197)
                      at android.view.View$PerformClick.run(View.java:20909)
                      at android.os.Handler.handleCallback(Handler.java:739)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:145)
                      at android.app.ActivityThread.main(ActivityThread.java:5944)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
    

    but in my case the WYSIWYG editor (IntelliJ w/Android Studio plugin) ended up populating the onClick property in activity_main.xml with some extra junk about MainActivity:

    android:onClick="sendMessage (MainActivity)"
    

    So I deleted " (MainActivity)" and it stopped crashing. I see this is different from your problem as your xml file already seems correct with android:onClick="sendMessage". But wanted to add it here for any others struggling with what I saw. This was the closest post to the issue I was seeing. I'm just getting started and this was killing me, so hope it helps someone else.

    0 讨论(0)
  • 2020-12-20 09:00

    The problem is the onClick property in one of your Button tags:

        android:onClick="sendMessage" />
    

    Just make sure you have a method sendMessage(View) in your Activity.

    0 讨论(0)
  • 2020-12-20 09:03

    It is because you need to implement implements android.view.View.OnClickListener in your class, therefore add the correct imports i.e. import android.view.View.

    0 讨论(0)
提交回复
热议问题