事件處理的基本概念
Android 所使用的事件處理方式,在視覺化介面上,是以傳統Java的 Listener 的方式,覆寫 Override 父類別中對映的事件函數的方式處理的,這和 VB 等設計方式很類似,在後面的文章中我們將使用一個簡單的按鈕控制示範這種覆寫處理法。
然而、在自訂的事件方面,Android是以 訊息傳遞的方式,搭配控制作業系統排程的方式處理的,這是一個相當奇特的處理方式,也使得初學者很難理解這種概念,在
後面的文章中、我們將使用此種方式,設計一個小的電子鐘,以說明此種訊息傳遞的事件處理方式。
按鈕事件
滑鼠事件
鍵盤事件
第1節 在程式中取得元件
取得上層元件
使用 R.id….. 可取得 layout 中用XML所定義的視覺化元件。
取得內層元件
使用 Activity.findViewById 可取得內層的元件,
TextView msgTextView = (TextView)findViewById(R.id.msg);
msgTextView.setText(R.string.push_me);
第2節 撰寫事件驅動函數
Listening for UI Notifications
Some UI notifications are automatically exposed and called by Android. For instance, Activity exposes overrideable methods onKeyDown and onKeyUp, and Widget exposes onFocusChanged(boolean, int). However, some important callbacks, such as button clicks, are not exposed natively, and must be registered for manually, as shown here
public class SendResult extends Activity
{
/**
* Initialization of the Screen after it is first created. Must at least
* call setContentView() to
* describe what is to be displayed in the screen.
*/
protected void onCreate(Bundle savedValues)
{
...
// Listen for button clicks.
Button button = (Button)findViewById(R.id.corky);
button.setOnClickListener(mCorkyListener);
}
// Create an anonymous class to act as a button click listener.
private OnClickListener mCorkyListener = new OnClickListener()
{
public void onClick(View v)
{
// To send a result, simply call setResult() before your
// activity is finished.
setResult(RESULT_OK, "Corky!");
finish();
}
};
第3節 一個簡單的按鈕範例
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button id="@+id/buttonHello"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Press me to say hello !"
/>
</LinearLayout>
package test.widget;
import test.widget.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class ButtonTest extends Activity {
Activity me;
Button buttonHello;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
me = this;
buttonHello = (Button) this.findViewById(R.id.buttonHello);
buttonHello.setOnClickListener(buttonHelloListener);
}
private View.OnClickListener buttonHelloListener
= new View.OnClickListener() {
public void onClick(View arg0) {
me.showAlert("Title", "Hello!", "OK", true);
}
};
}
時間事件
推薦給同仁
您想要瞭解更多的免費小竅門以便提升你的網站排名嗎?
請馬上聯繫我們網站管理員:
MSN: chenlinwu@cmmail.com
Email: info@rank-ad.com