是否可以为多个 Activity 使用一个 UI 处理程序?

发布于 2024-11-03 06:55:45 字数 35 浏览 5 评论 0原文

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

Hi I want to use only single handler for more than one Activity.Can I do that ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

寒尘 2024-11-10 06:55:45

为了在 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);
  }
}

To add a bit to Octavian answer, you will actually have a single Handler class but one instance per activity.

For example:

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();
    }
  }
}

Then in your activity:

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);
  }
}
So尛奶瓶 2024-11-10 06:55:45

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

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

public class ExternalClickListener implements View.OnClickListener {

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

}

现在,当您想将其设置在 Button 上时,它会是

btn.setOnClickListener(new ExternalClickListener());

Of course. Create a new class that implements the desired interface and instantiate it where needed.

Lets take the OnClickListener as an example. Create a class ExternalClickListener.

public class ExternalClickListener implements View.OnClickListener {

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

}

Now when you want to set it on a Button it'd be

btn.setOnClickListener(new ExternalClickListener());
倒带 2024-11-10 06:55:45

将此处理程序声明为static 并访问它:MyClass.myHandler

Declare this Handler as a static and access it : MyClass.myHandler.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文