我有一个复选框首选项,一旦单击它就会执行任务。如果任务失败,我想取消选中它。但我不确定为什么它不起作用。
首选项.xml:
<CheckBoxPreference
android:key="@string/premium_support"
android:title="Premium Support"
android:summary="Purchase premium support"
android:defaultValue="false" />
我将默认值设置为 false(未选中)。
我创建了一个实现更改侦听器的活动:
public class settingsActivity extends AppCompatActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
....
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new settingsFragment())
.commit();
PreferenceManager.setDefaultValues(this, R.xml.settings, false);
settings = PreferenceManager.getDefaultSharedPreferences(this);
settings.registerOnSharedPreferenceChangeListener(this);
settingPlayBilling();
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Toast.makeText(settingsActivity.this, "onSharedPreferenceChanged", Toast.LENGTH_SHORT).show();
mIabHelper.launchPurchaseFlow(settingsActivity.this, ITEM_SKU, 10001, mIabPurchaseFinishedListener, "mypurchasetoken");
}
但是,当检查应用内购买是否失败时:
mIabPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
@Override
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
if(result.isFailure()){
premium = false;
settings.getBoolean("premium_support", false);
return ;
}
else if(purchase.getSku().equals(ITEM_SKU)) {
premium = true;
settings.getBoolean("premium_support", true);
consumeItem();
}
}
};
问题是,即使应用内购买失败,复选框也会被标记。复选框会根据点击次数而变化。
任何帮助将不胜感激
当您执行以下操作时,您正在尝试读取共享首选项值:settings.getBoolean("premium_support", false);
要在共享首选项中保存值,您应该执行以下操作:settings.edit.putBoolean("premium_support", false).apply();
希望这会有所帮助。