当用户与视图views进行交互的时候,views也会触发事件。举个例子,当用户点击了一个按钮,你需要为 这个事件服务,只有这样,才能去执行某些适当的行为。如果想这么做的话,你就需要为视图views注册监听 。
使用上一节中的例子,在activity中有两个Button。我们可以使用一个匿名的类,为按钮设置点击 事件。
public class UIActivityActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //---the two buttons are wired to the same event handler--- Button btn1 = (Button)findViewById(R.id.btn1); btn1.setOnClickListener(btnListener); Button btn2 = (Button)findViewById(R.id.btn2); btn2.setOnClickListener(btnListener); } //---create an anonymous class to act as a button click listener--- private OnClickListener btnListener = new OnClickListener() { public void onClick(View v) { Toast.makeText(getBaseContext(), ((Button) v).getText() + " was clicked", Toast.LENGTH_LONG).show(); } }; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: Toast.makeText(getBaseContext(), "Center was clicked", Toast.LENGTH_LONG).show(); break; case KeyEvent.KEYCODE_DPAD_LEFT: Toast.makeText(getBaseContext(), "Left arrow was clicked", Toast.LENGTH_LONG).show(); break; case KeyEvent.KEYCODE_DPAD_RIGHT: Toast.makeText(getBaseContext(), "Right arrow was clicked", Toast.LENGTH_LONG).show(); break; case KeyEvent.KEYCODE_DPAD_UP: Toast.makeText(getBaseContext(), "Up arrow was clicked", Toast.LENGTH_LONG).show(); break; case KeyEvent.KEYCODE_DPAD_DOWN: Toast.makeText(getBaseContext(), "Down arrow was clicked", Toast.LENGTH_LONG).show(); break; } return false; } }
如果你点击了OK按钮或Cancel按钮,对应的消息就会出现在屏幕上,这也就说明了,适当的事件 被出发了。
开发入门(九)用户界面 9.3 注册事件监听器-java事件监听器原理">
除了定义一个匿名类,也可以定一个匿名内部类去处理事件。下面的例子展示如何 处理EditText的onFocusChange()方法。
//---create an anonymous inner class to act as an onfocus listener--- EditText txt1 = (EditText)findViewById(R.id.txt1); txt1.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { Toast.makeText(getBaseContext(), ((EditText) v).getId() + " has focus - " + hasFocus, Toast.LENGTH_LONG).show(); } });
以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索edittext
, button
, setonclicklistener
, 事件
, toast
, android监听edittext
, show
, button监听android
, PostgreSQL9.3
, button监听事件
, button监听
, KeyEvent
, Android注册界面
clicked
java事件监听器原理、activiti 事件监听器、android事件监听器、javascript事件监听器、js事件监听器,以便于您获取更多的相关知识。