如何从SharedPreference获取字号并应用到父子RecyclerView的文本控件
问题描述
我拥有父级和子级两个RecyclerView,已在设置界面修改字号并通过SaveData类完成保存。请问如何将SharedPreference中存储的字号应用到标题栏(Title Section)和文本项(Text Items)中?
现有代码
父级适配器代码
override fun onBindViewHolder(holder: ParentAdapter.MyViewHolder, position: Int) { holder.viewDataBinding.section.text = list[position].section holder.viewDataBinding.childRv.apply { adapter = ChildAdapter(list[position].list) } }
子级适配器代码
override fun onBindViewHolder(holder: ChildAdapter.MyViewHolder, position: Int) { holder.viewDataBinding.childText.text = list[position] }
页面代码
override fun onCreate(savedInstanceState: Bundle?) { val mainBinding = binding.mainRecycler mainBinding.apply { layoutManager = LinearLayoutManager(this@Activity) adapter = ParentAdapter(list) } }
数据存储类代码
class SaveData(context: Context) { private val sharedPreferences: SharedPreferences = context.getSharedPreferences("file", Context.MODE_PRIVATE) fun setFontSize(size: Float?) { val editor = sharedPreferences.edit() editor.putFloat("FontSize", size!!) editor.apply() } fun loadFontSize(): Float { val size = sharedPreferences.getFloat("FontSize", 0f) return size } }
解决方案
要实现字号的应用,需要在适配器中接收字号参数并设置到对应TextView,具体步骤如下:
- 在页面中加载保存的字号,传递给父级适配器
- 修改父级适配器,添加字号参数,设置标题字号并传递给子适配器
- 修改子级适配器,添加字号参数,设置文本项字号
修改后的代码
修改后的页面代码
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // 加载保存的字号,0f为默认值时设置默认字号 val saveData = SaveData(this) val fontSize = saveData.loadFontSize() val finalFontSize = if (fontSize == 0f) 14f else fontSize val mainBinding = binding.mainRecycler mainBinding.apply { layoutManager = LinearLayoutManager(this@Activity) // 将字号传递给父适配器 adapter = ParentAdapter(list, finalFontSize) } }
修改后的父级适配器代码
// 构造方法添加字号参数 class ParentAdapter(private val list: List<ParentModel>, private val fontSize: Float) : RecyclerView.Adapter<ParentAdapter.MyViewHolder>() { override fun onBindViewHolder(holder: ParentAdapter.MyViewHolder, position: Int) { holder.viewDataBinding.section.text = list[position].section // 设置标题字号 holder.viewDataBinding.section.textSize = fontSize holder.viewDataBinding.childRv.apply { // 将字号传递给子适配器 adapter = ChildAdapter(list[position].list, fontSize) } } // 其余原有代码(如ViewHolder、getItemCount等)保持不变 }
修改后的子级适配器代码
// 构造方法添加字号参数 class ChildAdapter(private val list: List<String>, private val fontSize: Float) : RecyclerView.Adapter<ChildAdapter.MyViewHolder>() { override fun onBindViewHolder(holder: ChildAdapter.MyViewHolder, position: Int) { holder.viewDataBinding.childText.text = list[position] // 设置文本项字号 holder.viewDataBinding.childText.textSize = fontSize } // 其余原有代码保持不变 }
补充说明
- 如果需要在修改字号后实时更新RecyclerView显示,可在设置界面修改字号后,通知页面重新创建适配器或调用适配器的
notifyDataSetChanged()方法 textSize方法接收的单位是sp,确保保存的字号值以sp为单位,若存储的是px值,需转换为sp后再设置
内容的提问来源于stack exchange,提问作者User_Michel
相关产品推荐
相关产品推荐

