Reputation: 71
I wish the amount to increase by 1 every time the "+" is clicked.
But now when I click "+", it shows like this
Problem(A): increment is red in android:onClick="increment" />
in activity_main.xml
Problem(B): I know I should write something inside () of increment()
and I have tried (1)increment(view: View?)
=> red alert: parameter 'view' is never used
shows up, but Problem (A) will be solved.
increment(view: View?)
is modified from java codes.
public void submitOrder(View view) {
display(1);
}
if I replace (view: View?) with something else then red alert: parameter 'view' is never used
disappears.
(2)increment(number:Int)
(3)increment()
None of them works. (2)(3) will result Unfortunately, Order Coffee has stopped.
Here is my MainActivity.kt
class MainActivity : AppCompatActivity() {
var amount: Int=2
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun increment() {
amount++
display(amount)
}
//This method is called when the order button is clicked.
fun submitOrder() {
var amount: Int=2
display(amount)
displayPrice(amount*10)
}
fun decrement() {
amount--
display(amount)
}
//This method displays the given quantity value on the screen.
private fun display(number: Int) {
val amountTextView = findViewById<View>(R.id.amount_text_view) as TextView
amountTextView.text = "" + number
}
/**
* This method displays the given price on the screen.
*/
private fun displayPrice(number: Int) {
val priceTextView = findViewById<View>(R.id.price_text_view) as TextView
priceTextView.setText(NumberFormat.getCurrencyInstance().format(number))
}
}
Upvotes: 0
Views: 254
Reputation: 19524
It doesn't matter if you don't use the view parameter in your onClick method, you can ignore the warning - it's just a cleanup hint, it should be yellow not red. (It's also wrong in this case, because you know you need that View
parameter! The compiler doesn't know about the onClick
attribute in the XML though, so it thinks it's unused)
If it says the app has stopped, that's a crash and there should be an error log saying where it crashed and why - the crashes you're getting are probably because you're changing the signature of your onClick
function. An onClickListener
has a single View
parameter, so whatever function you use has to match that.
Because you're saying "look for a function called this and use that as the click listener" in your XML file, it doesn't know what that function's going to be until you run the app and try clicking a thing. If you want to do it in code instead, you can do:
plusButton.setOnClickListener() { increment() }
which technically still has the View
passed in, as a variable called it
by default, but we're not using it so we can just ignore it! I prefer doing things in code like this personally, setting it in XML is kinda brittle and unhelpful sometimes (like you've discovered) but it's just a personal choice really
Upvotes: 1