Ana-Maria Curca
Ana-Maria Curca

Reputation: 83

Dynamically change Menu items

I have a menu item that allows the user turn gps on and off.In onCreate() the activity checks the status of the gps and uses the appropriate resources(2 different icons).How do I dynamically update the item icons?I've tried the code below, but i have a lag : the user has to push the item and enter Location and Security settings twice for the menu to be updated. Thank you.

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub

         switch (item.getItemId()) {
           case R.id.GPS:
            startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {

            item.setIcon(R.drawable.gps_off);

        } else {
            item.setIcon(R.drawable.gps);
        }

        break;

}

Upvotes: 0

Views: 1477

Answers (1)

waqaslam
waqaslam

Reputation: 68177

you have to override onPrepareOptionMenu in order to depict your changes every time the menu is constructed. Follow the example:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
     MenuItem mi = (MenuItem) menu.findItem(R.id.GPS);

     LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

     /*do your changes with its icon*/
     item.setIcon(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)? R.drawable.gps_off : R.drawable.gps);

     return super.onPrepareOptionsMenu(menu);
}

Upvotes: 2

Related Questions