2017-04-12 29 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

看到我編輯的答案。感謝您的反饋 :) –

相關問題