0

我在 MainActivity 中存储了一个名为“tgpref”的值。

SharedPreferences.Editor editor = preferences.edit();
           editor.putBoolean("tgpref", true); //value to save
           editor.commit();"

在我的 onCreate 我有

public SharedPreferences preferences;
---
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
preferences = getPreferences(MODE_PRIVATE);

我想在我的小部件中显示值,所以我尝试在小部件提供程序类的 onUpdate 中写入

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        boolean tgpref = preferences.getBoolean("tgpref", false)
        if (tgpref == true) { 
        remoteViews.setTextViewText(R.id.battery, "Risp on");
      } else {
        remoteViews.setTextViewText(R.id.battery, "Risp off");
      }

如果单击 MainActivty 中的切换按钮,我希望在我的小部件中显示“Risp on”,否则“Risp off”。现在只显示“Risp off”,所以我不知道该怎么做。有什么帮助吗?什么也没发生,我无法加载值

4

1 回答 1

0

它看起来不错,所以我猜您的按钮不会触发值更改?!

主要活动

private Boolean mTgpref;
private SharedPreferences prefs;
@Override
protected void onCreate(Bundle savedInstanceState) {

   //...
   //get value from shared preferences and update ui
   prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
   mTgpref = prefs.getBoolean("tgpref", false);
   setYourText();

}

private void setYourTextAndStoreToSharedPref(){   
    Log.i("TEST","mTgpref -> " + mTgpref); //check value 
    if(mTgpref){        
       remoteViews.setTextViewText(R.id.battery, "Risp on");
    }
    else
    {
       remoteViews.setTextViewText(R.id.battery, "Risp off");
    }
    prefs.edit().putBoolean("tgpref", mTgpref).commit();

    //UPDATE YOUR WIDGET HERE
}    

//function called on switch button click    
private void onSwitchClickButtonClick(){
    mTgpref = !mTgpref;   //toggle Boolean
    setYourText();
}

编辑 对不起,我误解了你的主要问题。更新 SharedPreferences 后,您应该按照此处描述的步骤操作:http: //developer.android.com/guide/topics/appwidgets/index.html#UpdatingFromTheConfiguration

于 2013-08-23T15:24:35.643 回答