您可以在佈局文件中使用android:onClick="anyMethodName"
屬性爲您的按鈕 ,例如:
<Button
android:id="@+id/button_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="myMethod"
android:text="Update" />
,並在你的類創建一個同名的方法是這樣的:
public void myMethod(View v){ // must use same name as in XML
// Perform action on click, this works like onClick() of anonymous inner class
Toast.makeText(this, "button clicked", Toast.LENGTH_SHORT).show();
}
只要在上面的方法中放入你想要放入你的匿名內部類的onClick()
中的任何東西,它就像魅力一樣工作。
的另一種方式是實現OnClickListener
接口,然後簡單地把所有的邏輯在一個單一的onClick(View v)
方法,通過註冊它的聽衆是這樣的:
button.setOnClickListener(this);
檢查我回答 –
你可以讓你的類實現OnClickListener,然後'button.setOnClickListener(this)'。你也可以使用butterknife來注入視圖。 – Raghunandan
@ X.LINK請在StackOverFlow上學習[upvote](http://stackoverflow.com/help/someone-answers)和[Accept Answers](http://stackoverflow.com/help/accepted-answer),它會鼓勵用戶幫助你。 –