Home > Mobile >  How do I use a string value instead of hardcoded text in a class in Android Studio?
How do I use a string value instead of hardcoded text in a class in Android Studio?

Time:06-17

This is my code in my class for my app. I am essentially displaying three expandable lists. Instead of adding the text to this class, how can I add a string instead? I've tried the way you add string to xml but does not work.

I need the ability to format text too, like change the size or embolden. Anyone what code type I need to use?

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
 import java.util.*

class ItemsFragment : Fragment() {

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    val rootView = inflater.inflate(R.layout.fragment_list, container, attachtoroot: false)

    val parent1 = Parent(id:0, title:"MAC")
    val childItems1 = ArrayList<Child>()
    childItems1.add(Child(parent1, id:0, title:"Sample Text here"))
    parent1.childItems.clear()
    parent1.childItems.addAll(childItems1)

    val parent2 = Parent(id:1, title:"Stack")
    val childItems2 = ArrayList<Child>()
    childItems2.add(Child(parent2, id:9, title:"Joy"))
    childItems2.add(Child(parent2, id:10, title:"King))
    childItems2.add(Child(parent2, id:11, title:"Wink"))
    parent2.childItems.clear()
    parent2.childItems.addAll(childItems2)

    val parent3 = Parent(id:2, title:"TESO")
    val childItems3 = ArrayList<Child>()
    childItems3.add(Child(parent3, id:12, title:"Sting))
    childItems3.add(Child(parent3, id:13, title:"Run))
    childItems3.add(Child(parent3, id:14, title:"Fridge"))
    parent3.childItems.clear()
    parent3.childItems.addAll(childItems3)

    val itemList = ArrayList<Item>()
    itemList.add(parent1)
    itemList.add(parent2)
    itemList.add(parent3)

    val list = rootView.findViewById<RecyclerView>(R.id.list)
    list.adapter = ItemsAdapter(itemList)

    return rootView
}

companion object {
    fun getInstance() = ItemsFragment()
}
}

CodePudding user response:

  • Related