Android事件处理机制
Android提供了两套事件处理机制,分别是:
- 基于监听的事件处理
- 基于回调的事件处理
监听事件处理模型
- Event Source --> 任意界面组件都可作为事件源
- Event --> 系统自动产生
- Event Listener --> 程序员自己处理
主要分为以下几步:
- 获取事件源,也就是被监听的对象
- 实现监听器类
- 调用事件源的setListener方法将事件监听器注册给普通组件
package com.lightless.eventqs;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get App's bn button
Button bn = (Button) findViewById(R.id.bn);
// Bind listener to button
bn.setOnClickListener(new MyClickListener());
}
// Define a Listener
class MyClickListener implements View.OnClickListener {
@Override
public void onClick(View arg0) {
EditText editText = (EditText) findViewById(R.id.txt);
editText.setText("Button has been clicked!");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}