首页 > 代码库 > Android Button事件处理

Android Button事件处理

一般只需要处理按钮的点击事件就可以,但想让一个按钮处理多个事件,就得同时监听多个方法。

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事件处理