2017-04-12 25 views
0

我想OnClick方法front()添加到我的按钮。然而,当我点击按钮,它返回此错误:java.lang.IllegalStateException:无法在Android的父母或祖先上下文找到方法:onclick属性

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:

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(); 
    } 

} 

任何想法的问题是什么?

+0

我建议你设置一个'onClickListener'直接在代码中是最好的方式,它永远不会失败,你不需要申报等等主代码中有许多功能。 –

回答

1

您的front method在您的活动中应该是public。你现在已经私下了。

这也描述在Android Developer网站上。

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(); 
} 
0

这是一个点击的动作是如何通过活动给按钮。

front.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Toast.makeText(this, "String", Toast.LENGTH_LONG).show(); 

      } 
     }); 

要通过XML onClick给按钮动作,

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

该方法也是正确的。你可以在xml中定义点击 –

+0

都是正确的 –

+0

看到我编辑的答案。感谢您的反馈 :) –

相关问题