在另一项活动中加载偏好?

时间:2013-08-23 13:52:59

标签: android android-widget sharedpreferences textview

我在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”所以我不知道我该怎么做。有帮助吗?什么都没发生我无法加载值

1 个答案:

答案 0 :(得分:0)

它看起来不错,所以我猜你的按钮不会触发价值变化?!

MainActiviy

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