简体   繁体   中英

Get state of Toggle Button in different class android

I have used ToggleButton in my MAINACTIVITY.java. When it is on am fetching the current location from another class GPSLOCATION.java and updating to server.

<ToggleButton
            android:id="@+id/switch1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:onClick="onToggleClicked" />

public void onToggleClicked(View view) {
boolean on = ((ToggleButton) view).isChecked();

if (on) {
        update_alert();
        } else {            
            timerAlert.cancel();
   }        
}

But since its run by using TimerTask ie, If TOGGLEBUTTON is ON then for every one minute LOCATION is fetched and updated in server. Instead I want to get the state of TOGGLEBUTTON in the GPSLOCATION.java under onLocationChanged method and if ON then I need to update it to server, I know it is possible can anyone help me to get rid of this scenario.

So you want to get the current state of this button in another class?

Could you possibly use the EventBus ?

See: http://square.github.io/otto/

You could fire off an Event when the switch is toggled, and then @Subscribe to the event in the class you want to handle the updating to the server.

For example:

Register both of your classes with the EventBus (assuming you initialise the EventBus at application level) you can call this in onCreate :

MyApplication.getInstance().getBus().register(this); 

Or something along the lines, this will register the desired class to receive or be able to post events along the bus.

Make sure to do this in both classes!

Then you must create an event to be posted, something like:

    public class ToggleEvent {

    public ToggleEvent() {
        //
    }
}

And then Post the event when onToggled is called like so:

MyApplication.getInstance().getBus().post(new ToggleEvent());

Then in your GPSLocation class you can have a method like:

@Subscribe public void retrieveToggleEvent(ToggleEvent event) {...}

This will retrieve the event when it's triggered (ie when onToggle is called and the event is fired!). Then you should be able to post to the server in retrieveToggleEvent .

You can also pass useful data along the Bus by using simple getter methods. In your case it might be better to override onToggled then you can pass through the boolean state of the switch in the bus, and handle whether its true/false in your @Subscribe method of GPSLocation .

Since registering a bus in a class will stay in memory forever, you should think about unregistering the bus onDestroy :

MyApplication.getInstance().getBus().unregister(this);

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM