android教程之按钮事件与事件处理

一个android应用往往有好几十个页面,而负责在这些页面中跳转的功能就落到了这些按钮的身上.按钮肩负的系统与用户之间的交互工作.下面我们来看下,在android中有哪些常见的监听器:

监听器 方法 内容
OnClickListener onClick 监听点击事件,用户点击或按下导航键时调用
OnLongClickListener onLongCick 监听长按事件,用户点击或按住导航键时调用
OnKeyListener onKey 监听物理按键,用户点击或松开物理键时调用
OnTouchListener onTouch 监听触摸实际那,用户执行触摸操作是调用(点击,滑动,弹起等)


button.xml

  <Button 
        android:id="@+id/bt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button"/>
	<TextView 
	    android:id="@+id/text2"
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content"/>

TestButton.java

public class TestButton extends Activity{
	private Button bt;
	private TextView text2;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.button);
		bt=(Button) this.findViewById(R.id.bt);
		text2=(TextView) this.findViewById(R.id.text2);
		bt.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
				text2.setText("您按下了按钮");
			}
		});
		
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		float x=event.getX();
		float y=event.getY();
		
		switch (event.getAction()) {
		case MotionEvent.ACTION_MOVE:
			text2.setText("你滑动了屏幕");
			break;
		case MotionEvent.ACTION_DOWN:
			text2.setText("你点击了屏幕,坐标x:"+x+",坐标y:"+y);
			break;
		case MotionEvent.ACTION_UP:
			text2.setText("您松开了屏幕,坐标x:"+x+"坐标y:"+y);
			break;
		default:
			break;
		}
		return super.onTouchEvent(event);
	}
	
}

运行程序,就可以看看是什么效果了

原文地址:https://www.cnblogs.com/IntelligentBrain/p/5111303.html