简体   繁体   中英

How to get font size from shared preference to textView in recyclerView?

I have two recyclerView Parent and Child, and in Settings I changed font size, and in SaveData Class I saved this size. How to get font size from shared preference in Settings to section (Title Section) and items (Text Items)?

this is the Code:

1. in Parent Adapter:
override fun onBindViewHolder(holder: ParentAdapter.MyViewHolder, position: Int) {
        holder.viewDataBinding.section.text = list[position].section
        holder.viewDataBinding.childRv.apply {
            adapter = ChildAdapter(list[position].list)
        }
}

2. in Child Adapter:
override fun onBindViewHolder(holder: ChildAdapter.MyViewHolder, position: Int) {
        holder.viewDataBinding.childText.text = list[position]
}

3. in Activity:
override fun onCreate(savedInstanceState: Bundle?) {
val mainBinding = binding.mainRecycler
        mainBinding.apply {
            layoutManager = LinearLayoutManager(this@Activity)
            adapter = ParentAdapter(list)
        }
}

4. in SaveData Class:
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
    }
}

You can use SharedPreferences.OnSharedPreferenceChangeListener and get font when it is changed.

The correct way to change font size is via the Preference Library to create a settings screen and then create a custom attribute. And create different styles depending on each size.

You can read my Medium Article for a step by step guide.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM