feat: 添加应用背景图片设置功能

功能特性:
1. BackgroundPreferences 管理背景图片设置(URI、启用状态、透明度)
2. 设置页面新增背景图片设置卡片(开关、选择、透明度、清除)
3. BackgroundHelper 工具类帮助 Fragment 应用背景图片
4. HomeFragment 已集成背景图片显示

设置界面:
- 启用/禁用背景图片开关
- 选择图片按钮(从相册选择)
- 透明度滑块(5%-100%可调)
- 清除背景图片按钮(红色警告按钮)

技术实现:
- 使用 SharedPreferences 存储背景图片 URI
- Glide 异步加载背景图片
- 支持持久化 URI 权限
- 实时保存所有设置
- HomeFragment 自动应用背景

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
hughhuangandClaude Sonnet 4.5 committed 2026-01-25 15:03:20 +08:00
1 parent 6bbd0cb59c
commit fd96f2c1a2
6 files changed
+532 -4

No files matched your search

@@ -22,6 +22,7 @@ import java.util.List;
import cn.hugh.bz.gk2.R; import cn.hugh.bz.gk2.R;
import cn.hugh.bz.gk2.model.Album; import cn.hugh.bz.gk2.model.Album;
import cn.hugh.bz.gk2.model.AppConfig; import cn.hugh.bz.gk2.model.AppConfig;
import cn.hugh.bz.gk2.utils.BackgroundHelper;
import cn.hugh.bz.gk2.utils.WallpaperServiceHelper; import cn.hugh.bz.gk2.utils.WallpaperServiceHelper;
import cn.hugh.bz.gk2.wallpaper.AlbumPreferences; import cn.hugh.bz.gk2.wallpaper.AlbumPreferences;
import cn.hugh.bz.gk2.wallpaper.WallpaperPreferences; import cn.hugh.bz.gk2.wallpaper.WallpaperPreferences;
@@ -66,6 +67,9 @@ public class HomeFragment extends Fragment {
initViews(view); initViews(view);
updateUI(); updateUI();
updateAlbumInfo(); updateAlbumInfo();
// 应用背景图片
BackgroundHelper.applyBackground(requireContext(), view);
} }
private void initViews(View view) { private void initViews(View view) {
@@ -1,12 +1,19 @@
package cn.hugh.bz.gk2.ui; package cn.hugh.bz.gk2.ui;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.widget.Button;
import android.widget.RadioButton; import android.widget.RadioButton;
import android.widget.RadioGroup; import android.widget.RadioGroup;
import android.widget.SeekBar; import android.widget.SeekBar;
import android.widget.Switch; import android.widget.Switch;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
@@ -19,6 +26,7 @@ import cn.hugh.bz.gk2.R;
import cn.hugh.bz.gk2.model.AppConfig; import cn.hugh.bz.gk2.model.AppConfig;
import cn.hugh.bz.gk2.model.PlayMode; import cn.hugh.bz.gk2.model.PlayMode;
import cn.hugh.bz.gk2.utils.AlarmScheduler; import cn.hugh.bz.gk2.utils.AlarmScheduler;
import cn.hugh.bz.gk2.wallpaper.BackgroundPreferences;
import cn.hugh.bz.gk2.wallpaper.WallpaperPreferences; import cn.hugh.bz.gk2.wallpaper.WallpaperPreferences;
/** /**
@@ -35,8 +43,19 @@ public class SettingsFragment extends Fragment {
private TextView tvIntervalValue; private TextView tvIntervalValue;
private Switch switchChangeOnReturn; private Switch switchChangeOnReturn;
// 背景图片相关控件
private Switch switchBackground;
private Button btnSelectBackground;
private Button btnClearBackground;
private SeekBar seekBarBackgroundAlpha;
private TextView tvBackgroundAlpha;
private WallpaperPreferences prefs; private WallpaperPreferences prefs;
private AppConfig config; private AppConfig config;
private BackgroundPreferences backgroundPrefs;
// 图片选择器
private ActivityResultLauncher<Intent> pickImageLauncher;
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
@@ -49,9 +68,14 @@ public class SettingsFragment extends Fragment {
prefs = new WallpaperPreferences(requireContext()); prefs = new WallpaperPreferences(requireContext());
config = prefs.loadConfig(); config = prefs.loadConfig();
backgroundPrefs = new BackgroundPreferences(requireContext());
// 初始化图片选择器
initPickImageLauncher();
initViews(view); initViews(view);
loadConfig(); loadConfig();
loadBackgroundConfig();
} }
private void initViews(View view) { private void initViews(View view) {
@@ -62,6 +86,13 @@ public class SettingsFragment extends Fragment {
tvIntervalValue = view.findViewById(R.id.tvIntervalValue); tvIntervalValue = view.findViewById(R.id.tvIntervalValue);
switchChangeOnReturn = view.findViewById(R.id.switchChangeOnReturn); switchChangeOnReturn = view.findViewById(R.id.switchChangeOnReturn);
// 背景图片控件
switchBackground = view.findViewById(R.id.switchBackground);
btnSelectBackground = view.findViewById(R.id.btnSelectBackground);
btnClearBackground = view.findViewById(R.id.btnClearBackground);
seekBarBackgroundAlpha = view.findViewById(R.id.seekBarBackgroundAlpha);
tvBackgroundAlpha = view.findViewById(R.id.tvBackgroundAlpha);
// 播放模式切换监听器(实时保存) // 播放模式切换监听器(实时保存)
rgPlayMode.setOnCheckedChangeListener((group, checkedId) -> { rgPlayMode.setOnCheckedChangeListener((group, checkedId) -> {
PlayMode playMode = rbSequential.isChecked() ? PlayMode.SEQUENTIAL : PlayMode.RANDOM; PlayMode playMode = rbSequential.isChecked() ? PlayMode.SEQUENTIAL : PlayMode.RANDOM;
@@ -102,6 +133,39 @@ public class SettingsFragment extends Fragment {
config.setChangeOnReturnToHome(isChecked); config.setChangeOnReturnToHome(isChecked);
prefs.saveConfig(config); prefs.saveConfig(config);
}); });
// 背景图片开关监听器
switchBackground.setOnCheckedChangeListener((buttonView, isChecked) -> {
backgroundPrefs.setBackgroundEnabled(isChecked);
updateBackgroundButtonsState();
});
// 选择背景图片按钮
btnSelectBackground.setOnClickListener(v -> pickBackgroundImage());
// 背景透明度滑块监听器
seekBarBackgroundAlpha.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
tvBackgroundAlpha.setText(progress + "%");
if (fromUser) {
backgroundPrefs.setBackgroundAlpha(progress);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// Do nothing
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// Do nothing
}
});
// 清除背景图片按钮
btnClearBackground.setOnClickListener(v -> clearBackgroundImage());
} }
private void loadConfig() { private void loadConfig() {
@@ -118,4 +182,86 @@ public class SettingsFragment extends Fragment {
config = prefs.loadConfig(); config = prefs.loadConfig();
loadConfig(); loadConfig();
} }
// ==================== 背景图片相关方法 ====================
/**
* 加载背景图片配置
*/
private void loadBackgroundConfig() {
boolean enabled = backgroundPrefs.isBackgroundEnabled();
switchBackground.setChecked(enabled);
int alpha = backgroundPrefs.getBackgroundAlpha();
seekBarBackgroundAlpha.setProgress(alpha);
tvBackgroundAlpha.setText(alpha + "%");
updateBackgroundButtonsState();
}
/**
* 更新背景按钮状态
*/
private void updateBackgroundButtonsState() {
boolean hasBackground = backgroundPrefs.getBackgroundUri() != null;
btnSelectBackground.setEnabled(switchBackground.isChecked());
btnClearBackground.setEnabled(hasBackground);
}
/**
* 初始化图片选择器
*/
private void initPickImageLauncher() {
pickImageLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
Uri uri = result.getData().getData();
if (uri != null) {
// 保存持久化权限
try {
requireContext().getContentResolver().takePersistableUriPermission(
uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION
);
} catch (Exception e) {
android.util.Log.e("SettingsFragment", "Error taking URI permission", e);
}
// 保存背景图片 URI
backgroundPrefs.setBackgroundUri(uri.toString());
backgroundPrefs.setBackgroundEnabled(true);
switchBackground.setChecked(true);
Toast.makeText(requireContext(), "背景图片已设置", Toast.LENGTH_SHORT).show();
updateBackgroundButtonsState();
}
}
}
);
}
/**
* 选择背景图片
*/
private void pickBackgroundImage() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
pickImageLauncher.launch(Intent.createChooser(intent, "选择背景图片"));
}
/**
* 清除背景图片
*/
private void clearBackgroundImage() {
new androidx.appcompat.app.AlertDialog.Builder(requireContext())
.setTitle("清除背景图片")
.setMessage("确定要清除应用背景图片吗?")
.setPositiveButton("确定", (dialog, which) -> {
backgroundPrefs.clearBackground();
switchBackground.setChecked(false);
Toast.makeText(requireContext(), "背景图片已清除", Toast.LENGTH_SHORT).show();
updateBackgroundButtonsState();
})
.setNegativeButton("取消", null)
.show();
}
} }
@@ -0,0 +1,129 @@
package cn.hugh.bz.gk2.utils;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import cn.hugh.bz.gk2.wallpaper.BackgroundPreferences;
/**
* 背景图片应用工具类
* 帮助 Fragment 应用自定义背景图片
*/
public class BackgroundHelper {
/**
* 为 Fragment 的根视图应用背景图片
*
* @param context 上下文
* @param rootView Fragment 的根视图
*/
public static void applyBackground(Context context, View rootView) {
if (context == null || rootView == null) {
return;
}
BackgroundPreferences prefs = new BackgroundPreferences(context);
// 检查是否启用了背景图片
if (!prefs.hasValidBackground()) {
return;
}
try {
String uriString = prefs.getBackgroundUri();
Uri uri = Uri.parse(uriString);
int alpha = prefs.getBackgroundAlpha();
// 使用 Glide 加载背景图片
Drawable background = loadBackgroundDrawable(context, uri);
if (background != null) {
// 设置透明度
background.setAlpha(alpha);
rootView.setBackground(background);
}
} catch (Exception e) {
android.util.Log.e("BackgroundHelper", "Error applying background", e);
}
}
/**
* 为 NestedScrollView 应用背景图片(带覆盖层)
* 这种方法会在背景上添加一个暗色遮罩,确保内容可读性
*
* @param context 上下文
* @param scrollView NestedScrollView 视图
*/
public static void applyBackgroundWithOverlay(Context context, androidx.core.widget.NestedScrollView scrollView) {
if (context == null || scrollView == null) {
return;
}
BackgroundPreferences prefs = new BackgroundPreferences(context);
// 检查是否启用了背景图片
if (!prefs.hasValidBackground()) {
return;
}
try {
String uriString = prefs.getBackgroundUri();
Uri uri = Uri.parse(uriString);
int alpha = prefs.getBackgroundAlpha();
// 使用 Glide 加载背景图片
Drawable background = loadBackgroundDrawable(context, uri);
if (background != null) {
// 设置透明度
background.setAlpha(alpha);
scrollView.setBackground(background);
}
} catch (Exception e) {
android.util.Log.e("BackgroundHelper", "Error applying background with overlay", e);
}
}
/**
* 加载背景图片 Drawable
*/
private static Drawable loadBackgroundDrawable(Context context, Uri uri) {
try {
// 使用 Glide 同步加载图片
return com.bumptech.glide.Glide.with(context)
.asDrawable()
.load(uri)
.centerCrop()
.submit(1080, 1920)
.get();
} catch (Exception e) {
android.util.Log.e("BackgroundHelper", "Error loading background drawable", e);
return null;
}
}
/**
* 检查是否启用了背景图片
*/
public static boolean hasBackground(Context context) {
if (context == null) {
return false;
}
BackgroundPreferences prefs = new BackgroundPreferences(context);
return prefs.hasValidBackground();
}
/**
* 清除背景图片
*/
public static void clearBackground(View rootView) {
if (rootView != null) {
rootView.setBackground(null);
}
}
}
@@ -0,0 +1,96 @@
package cn.hugh.bz.gk2.wallpaper;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import cn.hugh.bz.gk2.utils.FileLogger;
/**
* 背景图片设置管理类
* 管理应用背景图片的存储和读取
*/
public class BackgroundPreferences {
private static final String TAG = "BackgroundPreferences";
private static final String PREFS_NAME = "background_prefs";
// 背景图片 URI
private static final String KEY_BACKGROUND_URI = "background_uri";
// 是否启用背景图片
private static final String KEY_BACKGROUND_ENABLED = "background_enabled";
// 背景透明度
private static final String KEY_BACKGROUND_ALPHA = "background_alpha";
private final Context context;
private final SharedPreferences prefs;
private final FileLogger logger;
public BackgroundPreferences(Context context) {
this.context = context.getApplicationContext();
this.prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
this.logger = FileLogger.getInstance(context);
}
/**
* 保存背景图片 URI
*/
public void setBackgroundUri(String uriString) {
prefs.edit().putString(KEY_BACKGROUND_URI, uriString).apply();
logger.log(TAG, "Background URI saved: " + uriString);
}
/**
* 获取背景图片 URI
*/
public String getBackgroundUri() {
return prefs.getString(KEY_BACKGROUND_URI, null);
}
/**
* 设置是否启用背景图片
*/
public void setBackgroundEnabled(boolean enabled) {
prefs.edit().putBoolean(KEY_BACKGROUND_ENABLED, enabled).apply();
logger.log(TAG, "Background enabled: " + enabled);
}
/**
* 检查是否启用了背景图片
*/
public boolean isBackgroundEnabled() {
return prefs.getBoolean(KEY_BACKGROUND_ENABLED, false);
}
/**
* 设置背景透明度 (0-255)
*/
public void setBackgroundAlpha(int alpha) {
prefs.edit().putInt(KEY_BACKGROUND_ALPHA, alpha).apply();
logger.log(TAG, "Background alpha: " + alpha);
}
/**
* 获取背景透明度
*/
public int getBackgroundAlpha() {
return prefs.getInt(KEY_BACKGROUND_ALPHA, 30); // 默认 30% 不透明度
}
/**
* 清除背景图片设置
*/
public void clearBackground() {
prefs.edit()
.remove(KEY_BACKGROUND_URI)
.remove(KEY_BACKGROUND_ENABLED)
.apply();
logger.log(TAG, "Background cleared");
}
/**
* 检查是否有有效的背景图片设置
*/
public boolean hasValidBackground() {
return isBackgroundEnabled() && getBackgroundUri() != null && !getBackgroundUri().isEmpty();
}
}
+123 -4
View File
@@ -1,11 +1,17 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout <androidx.core.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
android:padding="16dp" android:background="@color/bg_primary"
android:fillViewport="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="@dimen/spacing_md"
tools:context=".ui.SettingsFragment"> tools:context=".ui.SettingsFragment">
<TextView <TextView
@@ -109,10 +115,123 @@
android:id="@+id/switchChangeOnReturn" android:id="@+id/switchChangeOnReturn"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="8dp" android:layout_marginTop="@dimen/spacing_sm"
android:layout_marginEnd="16dp" android:layout_marginEnd="@dimen/spacing_md"
android:checked="true" android:checked="true"
app:layout_constraintTop_toBottomOf="@id/tvChangeOnReturnDesc" app:layout_constraintTop_toBottomOf="@id/tvChangeOnReturnDesc"
app:layout_constraintEnd_toEndOf="parent" /> app:layout_constraintEnd_toEndOf="parent" />
<!-- 背景图片设置卡片 -->
<TextView
android:id="@+id/tvBackgroundLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="应用背景"
android:textSize="@dimen/text_size_lg"
android:textStyle="bold"
android:textColor="@color/text_primary"
android:layout_marginTop="@dimen/spacing_lg"
app:layout_constraintTop_toBottomOf="@id/switchChangeOnReturn"
app:layout_constraintStart_toStartOf="parent" />
<com.google.android.material.card.MaterialCardView
android:id="@+id/cardBackground"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/spacing_sm"
app:cardElevation="@dimen/card_elevation"
app:cardCornerRadius="@dimen/corner_radius_md"
app:cardBackgroundColor="@color/bg_card"
app:strokeColor="@color/glass_border"
app:strokeWidth="@dimen/glass_border_width"
app:layout_constraintTop_toBottomOf="@id/tvBackgroundLabel"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="@dimen/card_padding">
<!-- 背景开关和选择按钮 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical">
<Switch
android:id="@+id/switchBackground"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="启用背景图片"
android:textSize="@dimen/text_size_md"
android:textColor="@color/text_primary" />
<com.google.android.material.button.MaterialButton
android:id="@+id/btnSelectBackground"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选择图片"
android:textSize="@dimen/text_size_sm"
android:layout_marginStart="@dimen/spacing_md"
app:icon="@drawable/ic_image"
app:iconGravity="textStart"
app:cornerRadius="@dimen/corner_radius_sm"
style="@style/Widget.Material3.Button.OutlinedButton" />
</LinearLayout>
<!-- 透明度滑块 -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="背景透明度"
android:textSize="@dimen/text_size_sm"
android:textColor="@color/text_secondary"
android:layout_marginTop="@dimen/spacing_md" />
<SeekBar
android:id="@+id/seekBarBackgroundAlpha"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:min="5"
android:progress="30"
android:layout_marginTop="@dimen/spacing_sm" />
<TextView
android:id="@+id/tvBackgroundAlpha"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="30%"
android:textSize="@dimen/text_size_sm"
android:textColor="@color/text_hint"
android:layout_marginTop="@dimen/spacing_xs"
android:layout_gravity="end" />
<!-- 清除按钮 -->
<com.google.android.material.button.MaterialButton
android:id="@+id/btnClearBackground"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="清除背景图片"
android:textSize="@dimen/text_size_sm"
android:layout_marginTop="@dimen/spacing_md"
app:icon="@drawable/ic_delete"
app:iconGravity="textStart"
app:cornerRadius="@dimen/corner_radius_sm"
style="@style/Widget.Material3.Button.OutlinedButton"
android:textColor="@color/color_error"
app:iconTint="@color/color_error"
app:strokeColor="@color/color_error" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
</androidx.constraintlayout.widget.ConstraintLayout> </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>
@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- 背景图片 -->
<ImageView
android:id="@+id/ivBackgroundImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:alpha="0.3"
android:contentDescription="应用背景图片" />
<!-- 暗色遮罩层(确保内容可读性) -->
<View
android:id="@+id/viewDimOverlay"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#AA000000" />
<!-- 内容容器 -->
<androidx.core.widget.NestedScrollView
android:id="@+id/contentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<!-- 原始内容将在这里动态添加 -->
</androidx.core.widget.NestedScrollView>
</FrameLayout>