標籤:
一般只需要處理按鈕的點擊事件就可以,但想讓一個按鈕處理多個事件,就得同時監聽多個方法。
OnClickListener 點擊事件
OnLongClickListener 長按事件
OnTouchListener 觸摸事件
同事監聽三個事件,只有 OnTouchListener 會被觸發。
package demo.button;import android.app.Activity;import android.os.Bundle;import android.view.ContextMenu;import android.view.ContextMenu.ContextMenuInfo;import android.view.MotionEvent;import android.view.View;import android.view.View.OnClickListener;import android.view.View.OnCreateContextMenuListener;import android.view.View.OnLongClickListener;import android.view.View.OnTouchListener;import android.widget.Button;import android.widget.Toast;public class TestButtonActivity extends Activity{ Button test = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); test = (Button) findViewById(R.id.test); test.setOnClickListener(new MyOnClickListener()); test.setOnLongClickListener(new MyOnLongClickListener()); test.setOnTouchListener(new MyOnTouchListener()); } class MyOnClickListener implements OnClickListener { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), "單擊事件", Toast.LENGTH_SHORT).show(); } } class MyOnLongClickListener implements OnLongClickListener { @Overridepublic boolean onLongClick(View v){Toast.makeText(getApplicationContext(), "長按事件", Toast.LENGTH_SHORT).show();return true;} } class MyOnTouchListener implements OnTouchListener {@Overridepublic boolean onTouch(View v, MotionEvent event){if (event.getAction() == MotionEvent.ACTION_DOWN){ Toast.makeText(getApplicationContext(), "按下按鈕事件", Toast.LENGTH_SHORT).show();} if (event.getAction() == MotionEvent.ACTION_UP){Toast.makeText(getApplicationContext(), "彈起按鈕事件", Toast.LENGTH_SHORT).show();} //返回true 表示事件處理完畢,會中斷系統對該事件的處理。false 系統會同時處理對應的事件return true;} }}
Android Button事件處理