java.lang.IllegalStateException:在android:onClick属性的父级或祖先上下文中找不到方法 [英] java.lang.IllegalStateException: Could not find method in a parent or ancestor Context for android:onClick attribute

查看:73
本文介绍了java.lang.IllegalStateException:在android:onClick属性的父级或祖先上下文中找不到方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将onClick方法 front()添加到我的Button中.但是,当我单击按钮时,它将返回此错误:

I'm trying to add the onClick method front() to my Button. However when I click on the Button it returns this error:

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

这是我的xml:

<Button
    android:id="@+id/front"
    android:onClick="front"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Text" />

Register.java:

Register.java:

public class Register extends AppCompatActivity {

    private Button front;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        front = (Button) findViewById(R.id.front);
    }

    private void front(View v) {
        Toast.makeText(Register.this, "String", Toast.LENGTH_LONG).show();
    }

}

有什么问题吗?

推荐答案

您活动中的 front方法应该是 public .您现在已将其设为私有.

Your front method in your activity should be public. You have made it private right now.

Android开发者网站中也对此进行了描述.

This is described in Android Developer site too.

为使此方法有效,该方法必须是公共的并且接受View作为其唯一参数

In order for this to work, the method must be public and accept a View as its only parameter

public void front(View v) {
    Toast.makeText(Register.this, "String", Toast.LENGTH_LONG).show();
}

这篇关于java.lang.IllegalStateException:在android:onClick属性的父级或祖先上下文中找不到方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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