Andy
Andy

Reputation: 129

get Switch-Button State in Fragment from Activity with Eventbus

I´ve got the following scenario: I have a MainActivity which hosts 3 Fragments (Tabs). In my Fragment I´ve got two Switch-Toggles, whose state I would like to publish to the hosting Activity (MainActivity) with EventBus. I´ve set up two onCheckedChangeListener (for each toggle) in the onCreateView inside the Fragment:

mSwitchPublish.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            ListenerEvent switchPub = new ListenerEvent();
            switchPub.setSwitchStatePublish(isChecked);
            EventBus.getDefault().post(switchPub);
            Log.d(TAG, "EVENTBUS: PUB fired " + isChecked);
        }
    });
    mSwitchSubscribe.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            ListenerEvent switchSub = new ListenerEvent();
            switchSub.setSwitchStateSubscribe(isChecked);
            EventBus.getDefault().post(switchSub);
            Log.d(TAG, "EVENTBUS: SUB fired " + isChecked);
        }
    });

In my MainActivity I´ve got the following methods:

@Subscribe(threadMode = ThreadMode.MAIN)
public void handlePubSwitch(ListenerEvent switchPub) {
    if (switchPub.getSwitchStatePublish()) {
        switchPubChecked = true;
        Log.d(TAG, "EVENTBUS: PUB receive " + switchPub);
    } else {
        switchPubChecked = false;
        Log.d(TAG, "EVENTBUS: PUB receive " + switchPub);
        // do something else
    }
}

@Subscribe(threadMode = ThreadMode.MAIN)
public void handleSubSwitch(ListenerEvent switchSub) {
    if (switchSub.getSwitchStateSubscribe()) {
        switchSubChecked = true;
        Log.d(TAG, "EVENTBUS: SUB received " + switchSub);
        // do something
    } else {
        switchSubChecked = false;
        Log.d(TAG, "EVENTBUS: SUB received " + switchSub);
        // do something else
    }
}

Everytime I start the app, I´ll get an error:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: ***, PID: 4645
              org.greenrobot.eventbus.EventBusException: Subscriber class ***.fragments.HomeFragment and its super classes have no public methods with the @Subscribe annotation

I also had a look at a few similar topics here in Stackoverflow (and some more), but I´ve find no working solution...

Upvotes: 0

Views: 358

Answers (0)

Related Questions