Не удалось найти метод onClick (View) в активности

Щелчок кнопки в макете раздувания выходит из строя во время выполнения, потому что метод не может быть найден. E/AndroidRuntime (921): java.lang.IllegalStateException: Не удалось найти метод onClick (View) в активности но, если нажать на кнопку из основного макета, работайте хорошо. Что я сделал неправильно?

UPDATE: изменить код... stil fail... добавить журнал ошибок Я хочу, чтобы все мои кнопки обрабатывались методом ome.

основной класс активности

package com.android.insertview;


import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Toast;

public class InsertViewActivity extends Activity {
    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        /*LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        ViewGroup parent = (ViewGroup)findViewById(R.id.main_view);
        inflater.inflate(R.layout.volume_control, parent);*/

        LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);        
        View v = vi.inflate(R.layout.volume_control, null);    
        View insertPoint = findViewById(R.id.main_view);
        ((ViewGroup) insertPoint).addView(v, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT
                                                                            , ViewGroup.LayoutParams.WRAP_CONTENT));
    }


    public void btnclick(View v) {
        // TODO Auto-generated method stub
        Context context = getApplicationContext();
        Toast toast = Toast.makeText(context, 
            "This is Toast Notification", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();       
    }
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" android:id="@+id/main_view">
</LinearLayout>

раздувание макета

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" android:background="@drawable/service_button_container_background" 
    android:id="@+id/volume_view"> 

    <Button
        android:id="@+id/volume_up"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/button_volume_up" 
        android:onClick="btnclick" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/button_volume_mute_off" 
        android:onClick="btnclick"/>

    <Button
        android:id="@+id/volume_down"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/button_volume_down" 
        android:onClick="btnclick"/>

</LinearLayout>

журнал ошибок

03-19 15:31:45.184: W/dalvikvm(1071): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
03-19 15:31:45.184: E/AndroidRuntime(1071): Uncaught handler: thread main exiting due to uncaught exception
03-19 15:31:45.194: E/AndroidRuntime(1071): java.lang.IllegalStateException: Could not find a method genclick(View) in the activity
03-19 15:31:45.194: E/AndroidRuntime(1071):     at android.view.View$1.onClick(View.java:2020)
03-19 15:31:45.194: E/AndroidRuntime(1071):     at android.view.View.performClick(View.java:2364)
03-19 15:31:45.194: E/AndroidRuntime(1071):     at android.view.View.onTouchEvent(View.java:4179)
03-19 15:31:45.194: E/AndroidRuntime(1071):     at android.widget.TextView.onTouchEvent(TextView.java:6541)
03-19 15:31:45.194: E/AndroidRuntime(1071):     at android.view.View.dispatchTouchEvent(View.java:3709)
03-19 15:31:45.194: E/AndroidRuntime(1071):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
03-19 15:31:45.194: E/AndroidRuntime(1071):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
03-19 15:31:45.194: E/AndroidRuntime(1071):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
03-19 15:31:45.194: E/AndroidRuntime(1071):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
03-19 15:31:45.194: E/AndroidRuntime(1071):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
03-19 15:31:45.194: E/AndroidRuntime(1071):     at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1659)
03-19 15:31:45.194: E/AndroidRuntime(1071):     at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1107)
03-19 15:31:45.194: E/AndroidRuntime(1071):     at android.app.Activity.dispatchTouchEvent(Activity.java:2061)
03-19 15:31:45.194: E/AndroidRuntime(1071):     at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
03-19 15:31:45.194: E/AndroidRuntime(1071):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1691)
03-19 15:31:45.194: E/AndroidRuntime(1071):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-19 15:31:45.194: E/AndroidRuntime(1071):     at android.os.Looper.loop(Looper.java:123)
03-19 15:31:45.194: E/AndroidRuntime(1071):     at android.app.ActivityThread.main(ActivityThread.java:4363)
03-19 15:31:45.194: E/AndroidRuntime(1071):     at java.lang.reflect.Method.invokeNative(Native Method)
03-19 15:31:45.194: E/AndroidRuntime(1071):     at java.lang.reflect.Method.invoke(Method.java:521)
03-19 15:31:45.194: E/AndroidRuntime(1071):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
03-19 15:31:45.194: E/AndroidRuntime(1071):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
03-19 15:31:45.194: E/AndroidRuntime(1071):     at dalvik.system.NativeStart.main(Native Method)
03-19 15:31:45.194: E/AndroidRuntime(1071): Caused by: java.lang.NoSuchMethodException: genclick
03-19 15:31:45.194: E/AndroidRuntime(1071):     at java.lang.ClassCache.findMethodByName(ClassCache.java:308)
03-19 15:31:45.194: E/AndroidRuntime(1071):     at java.lang.Class.getMethod(Class.java:1014)
03-19 15:31:45.194: E/AndroidRuntime(1071):     at android.view.View$1.onClick(View.java:2017)
03-19 15:31:45.194: E/AndroidRuntime(1071):     ... 22 more

ОБНОВЛЕНИЕ 2:

ok, если я это сделаю, я могу обработать все кнопки, щелкнув одним способом genericClick()

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/front_end"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <!-- Main -->
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/main_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:background="@drawable/service_button_container_background" >

        <ImageButton
            android:id="@+id/radio"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/button_radio"
            android:clickable="true"
            android:onClick="genericClick" />

        <ImageButton
            android:id="@+id/player"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/button_player"
            android:onClick="genericClick" />

        <ImageButton
            android:id="@+id/navi"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/button_navigation"
            android:onClick="genericClick" />
    </LinearLayout>

    <!-- Volume controls -->
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/volume_controls"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:background="@drawable/service_button_container_background"
        android:orientation="vertical" >

        <ImageButton
            android:id="@+id/volume_up"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/button_volume_up"
            android:onClick="genericClick" />

        <ImageButton
            android:id="@+id/volume_mute"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/button_volume_mute_off"
            android:onClick="genericClick" />

        <ImageButton
            android:id="@+id/volume_down"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/button_volume_down"
            android:onClick="genericClick" />
    </LinearLayout>

    <!-- Radio controls -->
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/radio_controls"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/main_view"
        android:layout_marginRight="100dp"
        android:background="@drawable/service_button_container_background"
        android:visibility="invisible" >

        <ImageButton
            android:id="@+id/radio_preset"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="genericClick" android:background="@drawable/button_menu"/>

        <ImageButton
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/button_rewind"
            android:onClick="genericClick" />

        <ImageButton
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/button_play"
            android:onClick="genericClick" />

        <ImageButton
            android:id="@+id/button4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/button_forward"
            android:onClick="genericClick" />
    </LinearLayout>

    <!-- Radio Info -->
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/radio_info"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/radio_controls"
        android:layout_alignLeft="@+id/main_view"
        android:layout_marginLeft="100dp"
        android:background="@drawable/service_button_container_background"
        android:orientation="vertical" 
        android:visibility="invisible">

        <LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="FM"
                android:textSize="18.0px" />

            <TextView
                android:id="@+id/preset"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="1"
                android:textColor="#ffd6d6d6"
                android:textSize="18.0px" />

            <TextView
                android:layout_width="10.0dip"
                android:layout_height="wrap_content"
                android:text=" "
                android:textSize="18.0px" />

            <TextView
                android:id="@+id/frequency"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="108.0"
                android:textColor="#ffd6d6d6"
                android:textSize="18.0px" />
        </LinearLayout>

        <LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/title"
                android:layout_width="195.0dip"
                android:layout_height="24.0dip"
                android:text="Русское радио"
                android:textColor="#ffd6d6d6"
                android:textSize="18.0px" />
        </LinearLayout>
    </LinearLayout>
</RelativeLayout>

Ответы

Ответ 1

Удалите аннотацию @Override. Ознакомьтесь с официальной документацией для android: onClick - в своем случае метод обработчика selfDestruct (View).

Обновление:, как и другие, вы не должны использовать такое общее название для вашего метода обработчика событий - "onClick" является слишком общим. Что делать, если у вас есть 10 кнопок? Попробуйте что-то вроде "onClickLoginButton", "onClickSaveBtn" и т.д. Я думаю, вы не можете использовать "onClick" в качестве имени для метода четного обработчика, потому что View.OnClickListener имеет метод "onClick", поэтому вам нужно изменить имя в любом случае.

<Button
    android:id="@+id/volume_up"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/button_volume_up" 
    android:onClick="handleVolumeUp" />

И в вашем классе Activity

public void handleVolumeUp(View view) {
    // TODO Auto-generated method stub    
}

Удалите реализацию OnClickListener, чтобы определить определение вашего класса:

public class InsertViewActivity extends Activity

UPDATE2: Если вы хотите, чтобы все кнопки обрабатывались одним кликом-клиентом, выполните следующие действия:

@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button btn1 = (Button)findViewById(R.id.btn1);
    btn1.setOnClickListener(btnListener);
    Button btn2 = (Button)findViewById(R.id.btn2);
    btn2.setOnClickListener(btnListener);
    Button btn3 = (Button)findViewById(R.id.btn3);
    btn3.setOnClickListener(btnListener);
}

private OnClickListener btnListener = new OnClickListener()
{

    public void onClick(View v)
    {   
      //do the same stuff or use switch/case and get each button ID and do different   

      //stuff depending on the ID
    } 

};  

Ответ 2

Ваш метод не отменяется, поэтому удалите @Override

Чтобы избежать этого в будущем, вы можете создать свою собственную аннотацию, чтобы объявить свои методы, которые добавлены в макет Android XML.

Вот учебник для блога:

http://blog.blundell-apps.com/using-annotations-for-android-xml-onclick-visibility/

Ответ 3

Проблема в темах макетов для Android 5.X Основное действие не имеет темы тега в layout.xml другой имеет и это ошибка для ОС Android.

Решение находится здесь: android 5 и onClick в XML-макете

Вкратце: 1) удалить тег sheme из всех макетов; 2) добавить тег с правильной sheme в манифесте

Я попробовал для телефонов Android 5.X - он работает.

Ответ 4

Распространенная проблема, с которой я столкнулся, заключается в том, что начинающие будут объявлять метод onClick как защищенный или закрытый. Когда вы делаете это, механизм XML не может получить доступ к методу, который создает эту проблему.

Ответ 5

Является ли ваша вторая активность в файле manifest.xml?

Вам нужно добавить свою деятельность. См. Приведенный ниже код "Изменить вторую активность" в вашей деятельности. И укажите имя пакета, в котором находится ваша деятельность.

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="PackageName.MainActivity" android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity 
        android:name="PackageName.SecondActivityName" >     
    </activity>

</application>

Ответ 6

У меня такая же проблема. Я использовал <Button> вместо использования <android.support.v7.widget.AppCompatButton>. Я пробовал любой из методов, которые говорили другие люди. Но ни один из них не был хорошим ответом для меня. С этим небольшим изменением я смог преодолеть проблему.

Ответ 7

и вы должны отметить другое: public void onclick_method() {ваша логика;}. Студия не дает вам подсказки. Я просто пишу так и трачу много времени, чтобы найти ответ, наконец, я обнаружил, что правильный метод выглядит так: public void onclick_method (Просмотреть представление) {ваша логика;}  поэтому не забудьте указать параметр в скобке!

Blockquote