`

Android 中Observer模式的使用

阅读更多
android实际上使用了大量的obverser 模式,最简单的就是onclicklistener,但是与一般的observer模式不同的是,view中定义了很多接口,如下所示:
/**
    * Interface definition for a callback to be invoked when a touch event is
    * dispatched to this view. The callback will be invoked before the touch
    * event is given to the view.
    */
   public interface OnTouchListener {
       /**
        * Called when a touch event is dispatched to a view. This allows listeners to
        * get a chance to respond before the target view.
        *
        * @param v The view the touch event has been dispatched to.
        * @param event The MotionEvent object containing full information about
        *        the event.
        * @return True if the listener has consumed the event, false otherwise.
        */
       boolean onTouch(View v, MotionEvent event);
   }
 
   /**
    * Interface definition for a callback to be invoked when a view has been clicked and held.
    */
   public interface OnLongClickListener {
       /**
        * Called when a view has been clicked and held.
        *
        * @param v The view that was clicked and held.
        *
        * return True if the callback consumed the long click, false otherwise
        */
       boolean onLongClick(View v);
   }
 
   /**
    * Interface definition for a callback to be invoked when the focus state of
    * a view changed.
    */
   public interface OnFocusChangeListener {
       /**
        * Called when the focus state of a view has changed.
        *
        * @param v The view whose state has changed.
        * @param hasFocus The new focus state of v.
        */
       void onFocusChange(View v, boolean hasFocus);
   }
 
   /**
    * Interface definition for a callback to be invoked when a view is clicked.
    */
   public interface OnClickListener {
       /**
        * Called when a view has been clicked.
        *
        * @param v The view that was clicked.
        */
       void onClick(View v);
   }
 
   /**
    * Interface definition for a callback to be invoked when the context menu
    * for this view is being built.
    */
   public interface OnCreateContextMenuListener {
       /**
        * Called when the context menu for this view is being built. It is not
        * safe to hold onto the menu after this method returns.
        *
        * @param menu The context menu that is being built
        * @param v The view for which the context menu is being built
        * @param menuInfo Extra information about the item for which the
        *            context menu should be shown. This information will vary
        *            depending on the class of v.
        */
       void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
   }

每个接口执行不同的操作。

下面是一个相关的例子:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
 
public class Observer extends Activity implements OnClickListener ,OnFocusChangeListener{
    public static final String TITLE = "title";
 
    @Override
    public void setTitle(int titleId) {
        super.setTitle(titleId);
    }
 
    private Button btnMM;
    private Button btnMS;
    private Button btnSM;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.entry);
        findComponent();
        setOnClickListener();
        setOnFocusChangeListener();
 
    }
 
    private void setOnClickListener() {
        btnMM.setOnClickListener(this);
        btnMS.setOnClickListener(this);
        btnSM.setOnClickListener(this);
    }
 
     
    private void setOnFocusChangeListener() {
        btnMM.setOnFocusChangeListener(this);
        btnMS.setOnFocusChangeListener(this);
        btnSM.setOnFocusChangeListener(this);
    }
     
    private void findComponent() {
        btnMM = (Button) this.findViewById(R.id.btn_mm);
        btnMS = (Button) this.findViewById(R.id.btn_ms);
        btnSM = (Button) this.findViewById(R.id.btn_sm);
    }
 
    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
        case R.id.btn_mm:
            DebugLog.log("btnMM onclick");
            break;
        case R.id.btn_ms:
            DebugLog.log("btnMS onclick");
            break;
        case R.id.btn_sm:
            DebugLog.log("btnSM onclick");
            break;
        default:
            break;
        }
 
    }
 
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        int id = v.getId();
        switch (id) {
        case R.id.btn_mm:
            DebugLog.log("btnMM onFocusChange");
            break;
        case R.id.btn_ms:
            DebugLog.log("btnMS onFocusChange");
            break;
        case R.id.btn_sm:
            DebugLog.log("btnSM onFocusChange");
            break;
        default:
            break;
        }
         
    }
 
}

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
 
import android.util.Log;
 
public class DebugLog {
    public final static boolean DEBUG = true;
 
    public static void log(String message) {
        if (DEBUG) {
            String fullClassName = Thread.currentThread().getStackTrace()[3].getClassName();
            String className = fullClassName.substring(fullClassName.lastIndexOf(".") + 1);
            String methodName = Thread.currentThread().getStackTrace()[3].getMethodName();
            int lineNumber = Thread.currentThread().getStackTrace()[3].getLineNumber();
 
            Log.d(className + "." + methodName + "():" + lineNumber, message);
        }
    }
     
     
    public static void printThreadId(String message) {
        if (DEBUG) {
            Log.d(message, String.valueOf(Thread.currentThread().getId()));
        }
    }
 
    public static void log(String tag, String message) {
        if (DEBUG) {
            String methodName = Thread.currentThread().getStackTrace()[3].getMethodName();
            int lineNumber = Thread.currentThread().getStackTrace()[3].getLineNumber();
 
            Log.d(tag + "." + methodName + "():" + lineNumber, message);
        }
    }
 
    public static void printTrace(String message) {
        if (DEBUG) {
            printIllegalArgumentException("", message);
        }
    }
 
    public static String getStackTrace(Throwable throwable) {
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        throwable.printStackTrace(printWriter);
        return writer.toString();
    }
 
    public static void printIllegalArgumentException(String tag, String arg) {
        if (DEBUG) {
            final Throwable throwable = new IllegalArgumentException(arg);
            Log.w(tag, arg, throwable);
        }
    }
 
}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.fp.app.looper" android:versionCode="1"
    android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Observer" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest> 

<?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 android:id="@+id/btn_mm"  
    android:layout_width="fill_parent"  
    android:layout_height="wrap_content"  
    android:text="main thread to main thread" /> 
 <Button android:id="@+id/btn_ms"  
    android:layout_width="fill_parent"  
    android:layout_height="wrap_content"  
    android:text="main thread to sub thread" /> 
   <Button android:id="@+id/btn_sm"  
    android:layout_width="fill_parent"  
    android:layout_height="wrap_content"  
    android:text="sub thread to main thread" /> 
</LinearLayout> 
0
0
分享到:
评论

相关推荐

    Android observer 使用demo

    很可能包含了一个关于Observer模式的实战例子,可能涵盖了ContentObserver和BroadcastReceiver的使用,通过查看这个示例项目,你可以更深入地理解如何在Android应用中实现Observer模式,以及如何在实际项目中灵活...

    Android学习 ContentProvider数据更新与Observer模式.doc

    在Android开发中,ContentProvider和Observer模式是两个关键的概念,它们在数据管理和更新中起着重要作用。ContentProvider作为Android系统中数据共享的桥梁,允许不同的应用程序之间交换数据,而Observer模式则是一...

    android Observer(观察者模式)_案例祥解.pdf

    观察者模式是23种设计模式中的一种,尤其是在软件设计过程中体现的更是立足无穷。本文将详细讲解观察者模式的概念和实现,通过代码注释来解释各个组件的作用。 一、观察者模式的定义 观察者模式是一种行为设计模式...

    Android源码设计模式解析与实战.PDF(完整版)

    在Android开发过程中,经常使用的几种设计模式包括单例模式、观察者模式、工厂模式、装饰器模式等。每种模式都有其适用场景和独特优势,通过合理的运用,可以显著提升项目的质量和效率。 ### 单例模式详解 #### ...

    Android源码设计模式

    3. **观察者模式** (Observer): `BroadcastReceiver`是Android中的典型观察者模式,它监听特定的广播事件并做出响应。当某个事件发生时,注册的接收器会接收到通知。 4. **适配器模式** (Adapter): `BaseAdapter`在...

    android常用设计模式

    Android 设计模式系列还包括工厂方法模式、抽象工厂模式、创建者模式、原型模式、单例模式、适配器模式、桥模式、组合模式、装饰模式、外观模式、享元模式、代理模式、解释器模式、模板方法模式、职责链模式、命令...

    Android源码设计模式解析与实战.pdf

    《Android源码设计模式解析与实战》这本书主要探讨了在Android开发过程中如何运用经典的设计模式来提高代码质量、可维护性和扩展性。本书不仅详细分析了Android系统内部使用的各种设计模式,还通过实战案例帮助读者...

    Android设计模式

    下面将详细探讨Android设计模式中的关键知识点。 1. 单例模式(Singleton):在Android中,单例模式用于确保一个类只有一个实例,并提供全局访问点。例如,Android系统的应用上下文(Context)就是通过单例模式管理的...

    设计模式之Observer

    例如,Web开发中的事件监听、JavaScript中的事件处理、Android中的BroadcastReceiver等都是Observer模式的实例。 在阅读《设计模式之Observer》这篇博文中,作者可能会深入解析Observer模式的实现细节,包括如何...

    Android-23种设计模式

    在Android的UI绘制中,复用`Drawable`和`View`可以使用享元模式。 17. **组合模式(Composite)**:将对象组合成树形结构以表示“部分-整体”的层次结构。Android的`ViewGroup`和`View`结构体现了组合模式。 18. **...

    一个类实现Android观察者模式(最简单实用的观察者模式)

    观察者模式是软件设计模式中的一种行为模式,它在Android开发中被广泛应用,尤其是在处理事件响应和组件间的通信。这个模式允许对象订阅另一个对象的状态变化,当被观察的对象发生改变时,所有订阅者都会被通知并...

    android学习日记-6 观察者模式与订阅者模式

    在Android中使用`EventBus`,开发者可以创建自定义事件类,然后在需要的地方发布这些事件。订阅者通过`@Subscribe`注解的方法来订阅感兴趣的事件,并通过`EventBus.getDefault().register(this)`进行注册。当事件被...

    Android 设计模式:(二)观察者模式 —— 让你的对象知悉现况

    在Android开发中,设计模式是提升代码质量和可维护性的重要工具。本文将深入探讨其中的一种——观察者模式(Observer Pattern)。观察者模式是一种行为设计模式,它定义了对象之间的一对多依赖关系,当一个对象的...

    observable-observer

    在Java中,`Observable`类和`Observer`接口是内置的实现,用于创建这种观察者模式。现在我们来详细探讨`Observable`和`Observer`的原理以及如何手动实现简单的`MyObservable`和`MyObserver`。 首先,`Observable`类...

    Android 设计模式学习之观察者模式应用实例

    在Java中,可以使用java.util.Observable和java.util.Observer接口来实现观察者模式。而在Android中,由于生命周期的管理,我们可以使用Livedata、RxJava等库来实现更高效、更灵活的观察者模式。 **实例解析** 假设...

    观察者模式以及在Android开发中的应用

    总结起来,观察者模式在Android开发中主要体现在BroadcastReceiver和ContentObserver的使用上,它们帮助开发者实现组件间的通信和数据同步,提高了代码的灵活性和可维护性。通过ContentProvider,Android提供了一个...

    android 源码设计模式

    1. **单例模式(Singleton)**:在Android中,例如`Application`类和`SystemService`的注册过程,就广泛使用了单例模式。单例确保一个类只有一个实例,并提供全局访问点,控制了对象的生命周期。 2. **工厂模式...

    Android 设计模式:(一)观察者模式 —— 封装行为的大局观

    例如,在`StrategyDemo`这个示例中,我们可以假设它演示了如何在Android应用中使用观察者模式来处理用户交互或数据变化。`StrategyDemo`可能包含以下几个关键部分: 1. **Subject(主题)**:这是被观察的对象,...

    两篇android设计模式[归纳].pdf

    本文将重点讨论在Android框架设计中常用的两种设计模式:Observer模式和Template Method模式。 1. **Observer模式**: Observer模式是一种行为设计模式,它定义了对象之间的一对多依赖关系,当一个对象的状态发生...

Global site tag (gtag.js) - Google Analytics