Capitalize each word in Kotlin Arraylist

2019-08-16 22:47发布

问题:

I know to capitalize the arraylist with strings as data can be done with

list.map({ it.capitalize()})which returns as a list.

Now, what if it's a data class instead of strings?

class MainActivity : AppCompatActivity() {
    val animals: ArrayList<Animals> = ArrayList()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        addAnimals()
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.addItemDecoration(DividerItemDecoration(this,DividerItemDecoration.VERTICAL))
        recyclerView.adapter = AnimalAdapter(this, animals)

    }
      data class Animals(val name: String, val type: String)

    fun addAnimals() {
        animals.add(Animals("dog","bark"))
        animals.add(Animals("cat","meow"))
        animals.add(Animals("owl","hoot"))
        animals.add(Animals("cheetah","roar, growl, snarl"))
        animals.add(Animals("raccoon","trill"))
        animals.add(Animals("bird","chirp"))
        animals.add(Animals("snake","hiss"))
        animals.add(Animals("lizard","?"))
        animals.add(Animals("hamster","squeak"))
        animals.add(Animals("bear","roar, growl"))
        animals.add(Animals("lion","roar, growl, snarl"))
        animals.add(Animals("tiger","roar, growl, snarl"))
        animals.add(Animals("horse","neigh"))
        animals.add(Animals("frog","croak"))
        animals.add(Animals("fish","?"))
        animals.add(Animals("shark","?"))
        animals.add(Animals("turtle","?"))
        animals.add(Animals("elephant","trumpet"))
        animals.add(Animals("cow","moo"))
        animals.add(Animals("beaver","?"))
        animals.add(Animals("bison","moo"))
        animals.add(Animals("porcupine","?"))
        animals.add(Animals("rat","woof"))
        animals.add(Animals("mouse","squeak"))
        animals.add(Animals("goose","honk, hiss"))
        animals.add(Animals("deer","bellow"))
        animals.add(Animals("fox","bark, howl, growl, bay"))
        animals.add(Animals("moose","bellow"))
        animals.add(Animals("buffalo","moo"))
        animals.add(Animals("monkey","scream, chatter"))
        animals.add(Animals("penguin","?"))
        animals.add(Animals("parrot","squawk"))
    }

AnimalAdapter:

private class AnimalAdapter(val context: Context, val items: ArrayList<Animals>) : RecyclerView.Adapter<ViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            return ViewHolder(LayoutInflater.from(context).inflate(R.layout.animal_item, parent, false))
        }

        override fun getItemCount(): Int {
            return items.size
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            holder.tvAnimalType?.text = items.get(position).name.capitalize()
            holder.tvAnimalSounds?.text = items.get(position).type.capitalize()
            holder.itemView.setOnClickListener {
                val alertDialog: AlertDialog.Builder = AlertDialog.Builder(context)
                alertDialog.setMessage("Success")
                    .setPositiveButton("Ok") { dialog, which -> dialog.dismiss()
                    }
                    .setNegativeButton("Cancel") { dialog, which -> dialog.dismiss()
                    }
                val alert = alertDialog.create()
                // set title for alert dialog box
                alert.setTitle("AlertDialogExample")
                // show alert dialog
                alert.show()
            }
        }
    }

    private class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        // Holds the TextView that will add each animal to
        val tvAnimalType = view.animal_type
        val tvAnimalSounds = view.animal_sounds
    }

P.S : I know that I can capitalize it in the adapter class while setting it, which I have already done. But what if I have to do that before passing the List to the adapter?

回答1:

The first option is adding a capitalized name while creating animal object. If that's not possible then you can pass animals list like this

recyclerView.adapter = AnimalAdapter(this, animals.map({Animals(it.name.capitalize(),it.type)}));


回答2:

Depending on what your needs are, you could either create an Animal object with already capitalized values:

class Animal(name: String, type: String) {
    val name: String = name.capitalize()
    val type: String = type.capitalize()
}

Note that in this case the Animal class is not a data class any more.

or map your list of animals before using it:

val mappedAnimals = animals.map { Animal(it.name.capitalize(), it.type.capitalize()) }
recyclerView.adapter = AnimalAdapter(this, mappedAnimals)


回答3:

I wouldn't use mapping to capitalise all strings. Actually, there is a better approach. You can capitalise those strings in a TextView, at view level.

Why do I think it is a better approach than changing your data?

You do not modify data. Now, your mapped model is different that original. It can be a source of mistakes, because Animal("Dog", "John") != Animal("DOG", "JOHN"). Also, when you change Animal class there is a chance that somewhere you should change something too.

Making the capitalisation at view level makes it much more easier to read, find and modify.

And it's easy:

<TextView>
    ...
    android:textAllCaps=true
</TextView>

@see: https://developer.android.com/reference/android/widget/TextView.html#attr_android:textAllCaps