如何解决错误:在父级或祖先的上下文中找不到方法onClick(View)for android:onClick [英] How to solve error: Could not find method onClick(View) in a parent or ancestor Context for android:onClick

查看:3922
本文介绍了如何解决错误:在父级或祖先的上下文中找不到方法onClick(View)for android:onClick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到有一些类似的问题,但到目前为止这些答案对我没有帮助。完整错误:

I have seen that there's been some similar questions but the answers to those haven't helped me so far. The full error:


java.lang.IllegalStateException:在父级或祖先语句中找不到方法onClick(View)
for android:onClick属性定义
视图类android.support.v7.widget.AppCompatButton,id为
'button_random'

java.lang.IllegalStateException: Could not find method onClick(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'button_random'

类( StartActivity.java ):

public class StartActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
    }

    public void onClick(View v) {
        Log.d("DEBUG", "CLICKED " + v.getId());
    }

}

XML( activity_start .xml ):

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

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Random Game"
        android:id="@+id/button_random"
        android:layout_gravity="center_horizontal"
        android:onClick="onClick" />
</LinearLayout>

我已将活动添加到AndroidManifest.xml。我有类似的活动,以同样的方式工作,我没有任何问题...

I have added the activity to the AndroidManifest.xml. I have similar activities that work in the same way and I don't have any problems with those...

有没有人看到我错过的东西或已经做了什么一个错误?

Does anyone see something where I am missing something or have made a mistake?

推荐答案

我遇到了同样的问题,在我的情况下,我更改了 Button 在XML中以 android.support.v7.widget.AppCompatButton 并且它有效。

I had the same problem and in my case, I changed Button in XML to android.support.v7.widget.AppCompatButton and it worked.

代码错误:

 <Button
        .... />

固定代码:

 <android.support.v7.widget.AppCompatButton
        .... />

这篇关于如何解决错误:在父级或祖先的上下文中找不到方法onClick(View)for android:onClick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆