Toggling state of Wifi on Options menu

纵饮孤独 提交于 2019-12-12 02:18:24

问题


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.


回答1:


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>


来源:https://stackoverflow.com/questions/8722173/toggling-state-of-wifi-on-options-menu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!