Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 技術基礎

Android 事件處理入門:以監聽器模型為核心的兩種寫法

編輯:Android 技術基礎

任何以 UI 為核心的程式,都離不開事件處理。試想一個畫面:點按鈕沒反應、輸入框打完字不會回應,那就像一個人聽不到聲音一樣。Android 提供了兩條路——基於監聽器的事件處理,以及基於回呼(callback)的事件處理,本章聚焦前者。

監聽器模型的三個角色

  • 事件來源 Event Source:事件的產生者,通常是各類元件,例如按鈕、視窗。
  • 事件物件 Event:封裝事件發生的具體資訊,監聽器需要這些細節時就從它身上取。
  • 事件監聽器 Event Listener:負責接收事件並做出對應處理。

相較於回呼式寫法,監聽器模型更貼近物件導向的直覺:元件只負責「發出訊號」,處理邏輯則交給獨立實作的監聽器類別。

第一種寫法:內部類當監聽器

把監聽器類別定義成當前 Activity 的內部類。它有两个好處:監聽器可以在同一個類別中重複使用;而且能直接存取外部類別的所有界面元件,不必再四處 findViewById。

1. activity_main.xml

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/userName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="34dp"
        android:ems="10">
        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/passWord"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/userName"
        android:layout_marginTop="18dp"
        android:ems="10"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/userName"
        android:layout_below="@+id/passWord"
        android:layout_marginTop="36dp"
        android:text="登錄" />

</RelativeLayout>

2. MainActivity.java

package com.genwoxue.edittextbutton;

import android.os.Bundle;
import android.app.Activity;
import android.widget.EditText;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

public class MainActivity extends Activity {

    private EditText tvUserName = null;
    private EditText tvPassword = null;
    private Button btnLogin = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvUserName = (EditText) super.findViewById(R.id.userName);
        tvPassword = (EditText) super.findViewById(R.id.passWord);
        btnLogin = (Button) super.findViewById(R.id.login);

        // 為按鈕註冊監聽事件
        btnLogin.setOnClickListener(new LoginOnClickListener());
    }

    // 事件監聽器
    private class LoginOnClickListener implements OnClickListener {
        public void onClick(View v) {
            String username = tvUserName.getText().toString();
            String password = tvPassword.getText().toString();
            String info = "用戶名:" + username + "☆☆☆密碼:" + password;
            Toast.makeText(getApplicationContext(), info, Toast.LENGTH_SHORT).show();
        }
    }
}

把這段程式拆開看,其實只有兩個動作:註冊(setOnClickListener(new LoginOnClickListener()))與定義監聽器(實作 OnClickListener 介面的內部類)。就這麼簡單。

第二種寫法:匿名內部類

如果監聽器只用一次、用完就不留,那麼匿名內部類更合適——不必額外命名一個類別。

版面檔完全不動,只改 Java 程式:

package com.genwoxue.anonymousinside;

import android.os.Bundle;
import android.app.Activity;
import android.widget.EditText;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

public class MainActivity extends Activity {

    private EditText tvUserName = null;
    private EditText tvPassword = null;
    private Button btnLogin = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvUserName = (EditText) super.findViewById(R.id.userName);
        tvPassword = (EditText) super.findViewById(R.id.passWord);
        btnLogin = (Button) super.findViewById(R.id.login);

        btnLogin.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                String username = tvUserName.getText().toString();
                String password = tvPassword.getText().toString();
                String info = "用戶名:" + username + "☆☆☆密碼:" + password;
                Toast.makeText(getApplicationContext(), info, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

兩種寫法對照

第①種分成兩塊:先註冊 btnLogin.setOnClickListener(new LoginOnClickListener()),再另外宣告一個內部類。

第②種等於把這兩塊合併,直接在註冊時把匿名類別寫完。

兩者執行效果完全相同。實務上的判斷標準很簡單:監聽器只服務單一元件、邏輯不長,用匿名內部類;若多個元件共用同一套邏輯,或程式碼需要被讀懂、被複用,就該獨立成內部類。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved