Android Material3设置页:如何实现整行触发主题切换
实现整行点击切换App主题
布局修改步骤
给「App Theme」所在的
FrameLayout添加点击交互属性,让整行区域具备点击能力并提供视觉反馈:- 新增
android:id="@+id/appThemeRow",方便后续在代码中绑定点击事件 - 添加
android:clickable="true"、android:focusable="true"开启点击响应 - 添加
android:foreground="?attr/selectableItemBackground",实现Material Design标准的点击波纹效果
- 新增
将右侧的
Button替换为TextView,让布局风格和下方设置项统一,同时给文本控件设置id用于后续更新显示内容:
修改后的「App Theme」区域布局代码:
<FrameLayout android:id="@+id/appThemeRow" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" style="@style/settings_preferences_layout" android:clickable="true" android:focusable="true" android:foreground="?attr/selectableItemBackground"> <TextView style="@style/settings_preferences" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:fontFamily="@font/custom_font" android:text="App Theme" android:textStyle="normal" /> <TextView android:id="@+id/currentThemeTv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right|center_vertical" android:text="System" android:textColor="?attr/colorOnSurface" android:layout_marginEnd="15dp" /> </FrameLayout>
代码逻辑实现
在你的Settings Activity中,绑定布局控件并设置点击事件,点击整行后弹出主题选择对话框,完成选择后更新显示文本并切换主题:
class Settings : AppCompatActivity() { private lateinit var currentThemeTv: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.settings) currentThemeTv = findViewById(R.id.currentThemeTv) val appThemeRow = findViewById<FrameLayout>(R.id.appThemeRow) appThemeRow.setOnClickListener { val themes = arrayOf("System", "Light", "Dark") AlertDialog.Builder(this) .setTitle("选择App主题") .setItems(themes) { _, which -> val selectedTheme = themes[which] currentThemeTv.text = selectedTheme // 根据选择切换主题模式 when(selectedTheme) { "System" -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) "Light" -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) "Dark" -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) } // 重启Activity让主题立即生效 recreate() } .show() } } }
补充说明
- 用
foreground属性添加波纹效果,是设置项的标准交互反馈,能让用户清晰感知点击操作 - 替换按钮为文本后,整体布局风格更协调,符合常规设置页面的视觉逻辑
recreate()方法会重启当前Activity让主题立即生效,如果你需要更平滑的过渡,可以后续优化,这是新手最易上手的实现方式
内容的提问来源于stack exchange,提问作者Bhuvan Venkat Ganesh.B
相关产品推荐
相关产品推荐

