Reputation: 1063
Hi I want to use only single handler for more than one Activity.Can I do that ?
Upvotes: 0
Views: 589
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
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
Reputation: 1613
Declare this Handler as a static
and access it : MyClass.myHandler
.
Upvotes: -2