Shared pref return 除了 SettingsActivity 之外的所有 Activity 总是默认值
Shared pref return always default value on all activities except SettingsActivity
我正在尝试在我的应用中实现深色模式。我决定使用共享首选项来保存暗模式的当前状态。问题是共享首选项总是 returns 除了 SettingsActivity 之外的所有活动的默认值。
我试过了:
- 使用
getSharedPreferences()
代替getPreferences()
- 更改首选项的名称
- 将
allowBackup
更改为 false
- 正在清除应用缓存
- 正在删除应用程序数据
我的manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.george.socialmeme">
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28"
tools:ignore="ScopedStorage" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="false"
android:icon="@drawable/app_logo"
android:label="@string/app_name"
android:requestLegacyExternalStorage="true"
android:roundIcon="@drawable/app_logo"
android:supportsRtl="true"
android:theme="@style/Theme.SocialMeme"
android:dataExtractionRules="@xml/data_extraction_rules">
<activity
android:name=".Activities.PostsOfTheMonthActivity"
android:exported="false" />
<activity
android:name=".Activities.UserProfileActivity"
android:exported="true" />
<activity
android:name=".Activities.FollowerInfoActivity"
android:exported="false" />
<activity
android:name=".Activities.NotificationsActivity"
android:exported="false" />
<activity
android:name=".Activities.PrivacyPolicyActivity"
android:exported="false" />
<activity
android:name=".Activities.WelcomeActivity"
android:exported="false" />
<activity
android:name=".Activities.AccountSettingsActivity"
android:exported="false" />
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-9627755439548346~7996414717" />
<activity
android:name=".Activities.SettingsActivity"
android:exported="false" />
<activity android:name=".Activities.SelectProfileImageActivity" />
<activity
android:name=".Activities.HomeActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|uiMode"
android:exported="true" />
<activity
android:name=".Activities.RegisterActivity"
android:exported="false" />
<activity
android:name=".Activities.LoginActivity"
android:exported="false" />
<activity
android:name=".Activities.SplashScreenActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|uiMode"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".Services.FirebaseNotificationService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
我的 HomeActivity 的一部分:
boolean isNightModeEnabled() {
SharedPreferences sharedPref = HomeActivity.this.getPreferences(MODE_PRIVATE);
return sharedPref.getBoolean("dark_mode", false);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
if (isNightModeEnabled()) {
// Using force apply because HomeActivity contains fragments
Resources.Theme theme = super.getTheme();
theme.applyStyle(R.style.AppTheme_Base_Night, true);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
}
我的设置活动:
public class SettingsActivity extends AppCompatActivity {
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
CustomIntent.customType(SettingsActivity.this, "right-to-left");
}
boolean isNightModeEnabled() {
SharedPreferences sharedPref = SettingsActivity.this.getPreferences(MODE_PRIVATE);
return sharedPref.getBoolean("dark_mode", false);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
if (isNightModeEnabled()) {
setTheme(R.style.AppTheme_Base_Night);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
AdView mAdView = findViewById(R.id.adView3);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
DatabaseReference bugRef = FirebaseDatabase.getInstance().getReference("bugs");
DatabaseReference feedbackRef = FirebaseDatabase.getInstance().getReference("feedback");
ImageButton backBtn = findViewById(R.id.imageButton);
TextView username = findViewById(R.id.textView49);
CardView account_settings = findViewById(R.id.cardView2);
Button logout = findViewById(R.id.button);
CardView bugReport = findViewById(R.id.cardView3);
CardView feedback = findViewById(R.id.cardView5);
CardView privacyPolicy = findViewById(R.id.cardView6);
SwitchCompat nightModeSwitch = findViewById(R.id.switch1);
nightModeSwitch.setChecked(isNightModeEnabled());
nightModeSwitch.setOnClickListener(view -> {
SharedPreferences sharedPref = SettingsActivity.this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
if (isNightModeEnabled()) {
// Disable night mode
editor.putBoolean("dark_mode", false);
editor.apply();
Toast.makeText(this, "Night mode disabled", Toast.LENGTH_SHORT).show();
}else {
// Enable Night mode
editor.putBoolean("dark_mode", true);
editor.apply();
Toast.makeText(this, "Night mode enabled", Toast.LENGTH_SHORT).show();
}
finish();
Intent intent = new Intent(SettingsActivity.this, SplashScreenActivity.class);
startActivity(intent);
});
privacyPolicy.setOnClickListener(view -> {
startActivity(new Intent(SettingsActivity.this, PrivacyPolicyActivity.class));
CustomIntent.customType(SettingsActivity.this, "left-to-right");
});
feedback.setOnClickListener(view -> {
AlertDialog.Builder dialog = new AlertDialog.Builder(SettingsActivity.this)
.setTitle("Feedback");
final EditText feedback_et = new EditText(SettingsActivity.this);
feedback_et.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
feedback_et.setHint("Tell us your opinion");
dialog.setView(feedback_et);
dialog.setPositiveButton("Okay", (dialogInterface, i) -> {
if (!feedback_et.getText().toString().isEmpty()) {
feedbackRef.child(user.getUid()).child(feedback_et.getText().toString());
}
dialogInterface.dismiss();
Toast.makeText(SettingsActivity.this, "Feedback report succeed!", Toast.LENGTH_SHORT).show();
}).setNegativeButton("Cancel", (dialogInterface, i) -> {
dialogInterface.dismiss();
}).show();
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(550, FrameLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(50, 6, 30, 6);
feedback_et.setLayoutParams(params);
});
bugReport.setOnClickListener(view -> {
AlertDialog.Builder dialog = new AlertDialog.Builder(SettingsActivity.this)
.setTitle("Bug report");
final EditText bug_et = new EditText(SettingsActivity.this);
bug_et.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
bug_et.setHint("Please describe the issue");
dialog.setView(bug_et);
dialog.setPositiveButton("Okay", (dialogInterface, i) -> {
if (!bug_et.getText().toString().isEmpty()) {
bugRef.child(user.getUid()).child(bug_et.getText().toString());
}
dialogInterface.dismiss();
Toast.makeText(SettingsActivity.this, "Bug report succeed!", Toast.LENGTH_SHORT).show();
}).setNegativeButton("Cancel", (dialogInterface, i) -> {
dialogInterface.dismiss();
}).show();
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(550, FrameLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(50, 6, 30, 6);
bug_et.setLayoutParams(params);
});
logout.setOnClickListener(view -> {
new AlertDialog.Builder(SettingsActivity.this)
.setTitle("Are you sure?")
.setMessage("Are you sure you want to log out?")
.setPositiveButton("Yes", (dialogInterface, i) -> {
auth.signOut();
finish();
startActivity(new Intent(SettingsActivity.this, WelcomeActivity.class));
CustomIntent.customType(SettingsActivity.this, "fadein-to-fadeout");
}).setNegativeButton("No", (dialogInterface, i) -> {
dialogInterface.dismiss();
}).show();
});
username.setText(user.getDisplayName());
account_settings.setOnClickListener(v -> {
startActivity(new Intent(SettingsActivity.this, AccountSettingsActivity.class));
CustomIntent.customType(SettingsActivity.this, "left-to-right");
});
backBtn.setOnClickListener(v -> onBackPressed());
}
}
你可以简单地这样做
获取共享首选项:
SharedPreferences s = getSharedPreferences("dark_mode" , MODE_PRIVATE);
boolean isNight = s.getBoolean("dark_mode" , false);
编辑共享首选项:
s.edit().putBoolean("dark_mode" , /*true or false*/ true);
另请注意,每个共享首选项中的密钥都是相同的
我正在尝试在我的应用中实现深色模式。我决定使用共享首选项来保存暗模式的当前状态。问题是共享首选项总是 returns 除了 SettingsActivity 之外的所有活动的默认值。
我试过了:
- 使用
getSharedPreferences()
代替getPreferences()
- 更改首选项的名称
- 将
allowBackup
更改为 false - 正在清除应用缓存
- 正在删除应用程序数据
我的manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.george.socialmeme">
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28"
tools:ignore="ScopedStorage" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="false"
android:icon="@drawable/app_logo"
android:label="@string/app_name"
android:requestLegacyExternalStorage="true"
android:roundIcon="@drawable/app_logo"
android:supportsRtl="true"
android:theme="@style/Theme.SocialMeme"
android:dataExtractionRules="@xml/data_extraction_rules">
<activity
android:name=".Activities.PostsOfTheMonthActivity"
android:exported="false" />
<activity
android:name=".Activities.UserProfileActivity"
android:exported="true" />
<activity
android:name=".Activities.FollowerInfoActivity"
android:exported="false" />
<activity
android:name=".Activities.NotificationsActivity"
android:exported="false" />
<activity
android:name=".Activities.PrivacyPolicyActivity"
android:exported="false" />
<activity
android:name=".Activities.WelcomeActivity"
android:exported="false" />
<activity
android:name=".Activities.AccountSettingsActivity"
android:exported="false" />
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-9627755439548346~7996414717" />
<activity
android:name=".Activities.SettingsActivity"
android:exported="false" />
<activity android:name=".Activities.SelectProfileImageActivity" />
<activity
android:name=".Activities.HomeActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|uiMode"
android:exported="true" />
<activity
android:name=".Activities.RegisterActivity"
android:exported="false" />
<activity
android:name=".Activities.LoginActivity"
android:exported="false" />
<activity
android:name=".Activities.SplashScreenActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|uiMode"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".Services.FirebaseNotificationService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
我的 HomeActivity 的一部分:
boolean isNightModeEnabled() {
SharedPreferences sharedPref = HomeActivity.this.getPreferences(MODE_PRIVATE);
return sharedPref.getBoolean("dark_mode", false);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
if (isNightModeEnabled()) {
// Using force apply because HomeActivity contains fragments
Resources.Theme theme = super.getTheme();
theme.applyStyle(R.style.AppTheme_Base_Night, true);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
}
我的设置活动:
public class SettingsActivity extends AppCompatActivity {
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
CustomIntent.customType(SettingsActivity.this, "right-to-left");
}
boolean isNightModeEnabled() {
SharedPreferences sharedPref = SettingsActivity.this.getPreferences(MODE_PRIVATE);
return sharedPref.getBoolean("dark_mode", false);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
if (isNightModeEnabled()) {
setTheme(R.style.AppTheme_Base_Night);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
AdView mAdView = findViewById(R.id.adView3);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
DatabaseReference bugRef = FirebaseDatabase.getInstance().getReference("bugs");
DatabaseReference feedbackRef = FirebaseDatabase.getInstance().getReference("feedback");
ImageButton backBtn = findViewById(R.id.imageButton);
TextView username = findViewById(R.id.textView49);
CardView account_settings = findViewById(R.id.cardView2);
Button logout = findViewById(R.id.button);
CardView bugReport = findViewById(R.id.cardView3);
CardView feedback = findViewById(R.id.cardView5);
CardView privacyPolicy = findViewById(R.id.cardView6);
SwitchCompat nightModeSwitch = findViewById(R.id.switch1);
nightModeSwitch.setChecked(isNightModeEnabled());
nightModeSwitch.setOnClickListener(view -> {
SharedPreferences sharedPref = SettingsActivity.this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
if (isNightModeEnabled()) {
// Disable night mode
editor.putBoolean("dark_mode", false);
editor.apply();
Toast.makeText(this, "Night mode disabled", Toast.LENGTH_SHORT).show();
}else {
// Enable Night mode
editor.putBoolean("dark_mode", true);
editor.apply();
Toast.makeText(this, "Night mode enabled", Toast.LENGTH_SHORT).show();
}
finish();
Intent intent = new Intent(SettingsActivity.this, SplashScreenActivity.class);
startActivity(intent);
});
privacyPolicy.setOnClickListener(view -> {
startActivity(new Intent(SettingsActivity.this, PrivacyPolicyActivity.class));
CustomIntent.customType(SettingsActivity.this, "left-to-right");
});
feedback.setOnClickListener(view -> {
AlertDialog.Builder dialog = new AlertDialog.Builder(SettingsActivity.this)
.setTitle("Feedback");
final EditText feedback_et = new EditText(SettingsActivity.this);
feedback_et.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
feedback_et.setHint("Tell us your opinion");
dialog.setView(feedback_et);
dialog.setPositiveButton("Okay", (dialogInterface, i) -> {
if (!feedback_et.getText().toString().isEmpty()) {
feedbackRef.child(user.getUid()).child(feedback_et.getText().toString());
}
dialogInterface.dismiss();
Toast.makeText(SettingsActivity.this, "Feedback report succeed!", Toast.LENGTH_SHORT).show();
}).setNegativeButton("Cancel", (dialogInterface, i) -> {
dialogInterface.dismiss();
}).show();
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(550, FrameLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(50, 6, 30, 6);
feedback_et.setLayoutParams(params);
});
bugReport.setOnClickListener(view -> {
AlertDialog.Builder dialog = new AlertDialog.Builder(SettingsActivity.this)
.setTitle("Bug report");
final EditText bug_et = new EditText(SettingsActivity.this);
bug_et.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
bug_et.setHint("Please describe the issue");
dialog.setView(bug_et);
dialog.setPositiveButton("Okay", (dialogInterface, i) -> {
if (!bug_et.getText().toString().isEmpty()) {
bugRef.child(user.getUid()).child(bug_et.getText().toString());
}
dialogInterface.dismiss();
Toast.makeText(SettingsActivity.this, "Bug report succeed!", Toast.LENGTH_SHORT).show();
}).setNegativeButton("Cancel", (dialogInterface, i) -> {
dialogInterface.dismiss();
}).show();
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(550, FrameLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(50, 6, 30, 6);
bug_et.setLayoutParams(params);
});
logout.setOnClickListener(view -> {
new AlertDialog.Builder(SettingsActivity.this)
.setTitle("Are you sure?")
.setMessage("Are you sure you want to log out?")
.setPositiveButton("Yes", (dialogInterface, i) -> {
auth.signOut();
finish();
startActivity(new Intent(SettingsActivity.this, WelcomeActivity.class));
CustomIntent.customType(SettingsActivity.this, "fadein-to-fadeout");
}).setNegativeButton("No", (dialogInterface, i) -> {
dialogInterface.dismiss();
}).show();
});
username.setText(user.getDisplayName());
account_settings.setOnClickListener(v -> {
startActivity(new Intent(SettingsActivity.this, AccountSettingsActivity.class));
CustomIntent.customType(SettingsActivity.this, "left-to-right");
});
backBtn.setOnClickListener(v -> onBackPressed());
}
}
你可以简单地这样做
获取共享首选项:
SharedPreferences s = getSharedPreferences("dark_mode" , MODE_PRIVATE);
boolean isNight = s.getBoolean("dark_mode" , false);
编辑共享首选项:
s.edit().putBoolean("dark_mode" , /*true or false*/ true);
另请注意,每个共享首选项中的密钥都是相同的