0

嗨,我只想对多个活动使用单个处理程序。我可以这样做吗?

4

3 回答 3

4

为了给 Octavian 的答案添加一点内容,您实际上将有一个 Handler 类,但每个活动都有一个实例。

例如:

public class MyHandler extends Handler {
  // Keep a weak reference to the activity owning the handler
  private WeakReference<Activity> activityRef;

  public MyHandler(Activity a) {
    this.activityRef = new WeakReference<Activity>(a);
  }

  public void handleMessage(Message msg) {
    // do your stuff here, for instance, finish the activity
    if (activityRef.get()!=null) {
      activityRef.get().finish();
    }
  }
}

然后在您的活动中:

public class MyActivity extends Activity {
  protected MyHandler handler;

  public void onCreate() {
    // This is where you'll re-use the handler code
    handler = new MyHandler(this);
  }
}
于 2011-04-26T13:21:33.483 回答
2

当然。创建一个实现所需接口的新类并在需要的地方实例化它。

让我们以OnClickListener为例。创建一个类ExternalClickListener

public class ExternalClickListener implements View.OnClickListener {

    @Override
    public void onClick(View v) {
        // Do whatever you want.
    }

}

现在,当您想将其设置Button

btn.setOnClickListener(new ExternalClickListener());
于 2011-04-26T13:14:20.537 回答
-2

将此 Handler 声明为 astatic并访问它:MyClass.myHandler

于 2011-04-26T13:04:53.627 回答