简体   繁体   中英

Toggling state of Wifi on Options menu

I would like to toggle the state of Wifi in options menu in Android. I would like to extend its functionality by showing two icons one for "switched on" and the other for "switched off". It should work in such a way that when a user presses the menu key:

  1. He should see current status of Wifi "on" or "off"
  2. The icons must be shown according to its state "on" or "off"
  3. When the user clicks the Wifi option it should toggle the state of Wifi and also change the icon accordingly

Is this possible to do in the options menu ?

Any ideas as to how to change the icons according to its state ?

So far I am able to toggle the Wifi state by taking the user to a different activity. But if I can achieve it in the options menu. It would make the app more easy to use.

Thank you for your input and for your time.

here is the code for wifi on/off :

 @Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.wifistate:
        final WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if(wifi.isWifiEnabled()){
            wifi.setWifiEnabled(false);
            Drawable drawable = getResources().getDrawable(R.drawable.off);
            item.setIcon(drawable);
        }else{
            Drawable drawable = getResources().getDrawable(R.drawable.on);
            item.setIcon(drawable);
            wifi.setWifiEnabled(true);
        }
        break;

    }
    return true;

}

manifest.xml (add permission)

<uses-permission
    android:name="android.permission.ACCESS_WIFI_STATE" />

menu.xml file :

<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"><item android:id="@+id/wifistate"  android:title="Off" android:icon="@drawable/off"/></menu>

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