如何通过共享首选项保存menuitem可见性状态? [英] how to save menuitem visibility state through sharedpreferences?

查看:69
本文介绍了如何通过共享首选项保存menuitem可见性状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,我在操作栏上添加了一个菜单项,称为添加到收藏夹,该菜单项由白色星形图标显示。当用户单击它时,该图标消失,并且其他黄色星形图标项目可见性出现了……这很好..但是问题是,当我切换到另一个活动或重新启动应用程序时,先前的事件已丢失。如何通过sharedpreferences保存它? ?..
这是我的代码。

Hi In my app I add a menuitem on the action bar called "add to favorite" shown by white star icon. When user click it this icon become disappear and other yellow star icon item visibility comes up...this works fine..but the problem is that when I switch to another activity or when I restart my app the previous event has been lost. How can I save this through sharedpreferences? ?.. Here my code.

On prepareoptionmenu (Menu menu){
If (ffavClicked){
menu.finditem (R.id.id_favorite).setvisible (false);
menu.finditem (R.id.id_favorite 2). setvisible (true);
}
else if (! favClicked){
menu.finditem ( R.id.id_favorite).setvisible (true);
menu.finditem (R.id.id_favorite 2).setvisible (false);
}
return ssuper . onprepareoptionmenu (menu);
}


推荐答案

我希望这能解决您的问题问题!

i hope this will solve your problem!

在您的活动中首先定义布尔值

in your activity define boolean first

public class Atherosclerosis extends Activity {

    boolean favClicked;

在创建时使用它。

setContentView(R.layout.activity_main);

        SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        favClicked = myPrefs.getBoolean("menu_item", false);

然后

 public boolean onOptionsItemSelected(MenuItem item) {


          SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(this);
          final SharedPreferences.Editor editor = myPrefs.edit();
          favClicked = myPrefs.getBoolean("menu_item", false);


          switch (item.getItemId()) {
           case R.id.id_favorit:
                favClicked=true;
                editor.putBoolean("menu_item", favClicked);
                editor.commit();
                invalidateOptionsMenu();
                return true;

            case R.id.id_favorit2:

                favClicked=false;
                editor.putBoolean("menu_item", favClicked);
                editor.commit();
                invalidateOptionsMenu();
                return super.onOptionsItemSelected(item); 
            }
        return true;
        }
           @Override
            public boolean onPrepareOptionsMenu(Menu menu) {


         if(favClicked==true){
               menu.findItem(R.id.id_favorit).setVisible(false);
                menu.findItem(R.id.id_favorit2).setVisible(true);

         }else{
           menu.findItem(R.id.id_favorit).setVisible(true);
            menu.findItem(R.id.id_favorit2).setVisible(false);

     }



                return super.onPrepareOptionsMenu(menu);
            }


   }

这篇关于如何通过共享首选项保存menuitem可见性状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆