Mak
Mak

Reputation: 1063

Is it possible to use One UI Handler For more than One Activity?

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

Upvotes: 0

Views: 589

Answers (3)

Octavian Helm
Octavian Helm

Reputation: 39605

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

Upvotes: 2

Vincent Mimoun-Prat
Vincent Mimoun-Prat

Reputation: 28551

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

Upvotes: 4

Kocus
Kocus

Reputation: 1613

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

Upvotes: -2

Related Questions