用户可以使用两种级别与你的UI进行交互,一种是activity级别,另一种是view级别。在activity级别,Activity类暴露了一些你可以重写的方法。有一些常用的方法,你可以在你的Activity中进行重写:
- onKeyDown
- onKeyUp
- onMenuItemSelected
- onMenuOpened
下面的例子重写了一些在activity中的方法,通过这个例子展示用户如何与众多的activity进行交互。
1、创建一个工程:UIActivity。
2、main.xml中的代码。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="214dp" android:layout_height="wrap_content" android:text="Your Name" /> <EditText android:id="@+id/txt1" android:layout_width="214dp" android:layout_height="wrap_content" /> <Button android:id="@+id/btn1" android:layout_width="106dp" android:layout_height="wrap_content" android:text="OK" /> <Button android:id="@+id/btn2" android:layout_width="106dp" android:layout_height="wrap_content" android:text="Cancel" /> </LinearLayout>3、UIActivityActivity.java中的代码。
package net.learn2develop.UIActivity; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; 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); } @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; } }4、按F11调试。
5、当这个activity被加载,在EditText中输入一些文字。然后,点击方向键中的向下的按钮。观察屏幕上的信息。