In our class this week, our assignment is to create a simple cake-baking app. There are two edit text fields(wetText, dryText) in which the user can input ingredients to add to the cake. There is a mixbutton that is clicked after adding the ingredients. On the mixbutton click, my goal is to list the added ingredients from the editText into a new textView(cakeText) as such:
You added --- to the batter!
You added --- to the batter!
You added --- to the batter!
etc.
We're supposed to use a for-loop, and I think I may be on the right track by using an array. The batterList was my most recent attempt at this, so I know it's wrong, but I'd love to know how to fix it! I've been working at it for hours and have gotten close, but not close enough. I hope this makes sense. My mind isn't working right at this point. Any advice would be greatly appreciated!
val wetList = mutableListOf<String>()
val dryList = mutableListOf<String>()
val batterList = arrayOf(wetList)
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun wetButtonTapped(view: View) {
wetList.add(wetText.text.toString())
wetText.text.clear()
ingredientList.text = "You have ${wetList.count()} wet ingredients \n You have ${dryList.count()} dry indredients"
}
fun dryButtonTapped(view: View) {
dryList.add(dryText.text.toString())
dryText.text.clear()
ingredientList.text = "You have ${wetList.count()} wet ingredients \n You have ${dryList.count()} dry indredients"
}
fun mixButtonTapped(view: View) {
//cakeText.text = "You added ${wetList}"
for (item in batterList){
cakeText.text = "You added $item to the batter!"
}
CodePudding user response:
You're always assigning the last line of your intended list into cakeText
.
Try this:
cakeText.text = "${cakeText.text}\nYou added $item to the batter!"
This should add the items one by one in the text.
Also, you may need to change batterList
from val
to var
and reassign it on mixButtonTapped
. So final code should look like this:
var batterList = arrayOf(wetList)
...
fun mixButtonTapped(view: View) {
batterList = arrayOf(wetList)
for (item in batterList){
cakeText.text = "${cakeText.text}\nYou added $item to the batter!"
}
}
CodePudding user response:
as far as i understand you want to show all added ingredients in single text view. so instead of declaring a new array which can be sometime unmanageable i will directly use both of array and StringBuilder class for building the whole string
fun mixButtonTapped(view: View) {
val stringBuilder = StringBuilder()
// here (wetList dryList) will be merged into single list
for (item in (wetList dryList))
stringBuilder.append("You added $item to the batter!\n")
cakeText.text = stringBuilder.toString()
}
so instead of managing third array i will directly use both array and dispose the merged array when my task is done in this case it will be when the loop is completed.