編輯:Android開發教程
當用戶與視圖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按鈕,對應的消息就會出現在屏幕上,這也就說明了,適當的事件 被出發了。
除了定義一個匿名類,也可以定一個匿名內部類去處理事件。下面的例子展示如何 處理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(); } });
步驟1:新建一個項目Compass,並將一張指南針圖片導入到res/drawable-hdpi目錄中步驟2:設計應用的UI界面,main.xml<?xml vers
ActivityInstrumentationTestCase2 用來測試單個的Activity,被測試的Activity可以使用InstrumentationTestC
這段時間的自定義View學習,學會了繪制柱狀圖、繪制折線圖、繪制進度控件,那我們今天就來聊聊另外一種自定義的View,這就是我們常見的七日年化收益折線圖效果。先看看長什麼
AndroidGraphics2DTutorial定義了應用的主Activity,下面就可以開始寫每個具體的二維繪圖示例。不同的例子將盡量采用 不同的UI控件:Menu,