Day35 of #100DaysOfCode

Kushagra Kesav
2 min readMar 13, 2022

--

#CodeTogether Day 35/100

Hii folks 🙌

Today I continued the lesson of the same Pathway 4, where I created an interactive dice roller app.

Unit 1: Kotlin basics

Pathway 4: Add a button to an app

Source: https://developer.android.com/courses/android-basics-kotlin/course

Create an interactive Dice Roller app

  • The top-level or first activity is often called the MainActivity and is provided by the project template. For example, when the user scrolls through the list of apps on their device and taps on the "Dice Roller" app icon, the Android System will start up the MainActivity of the app.
class MainActivity : AppCompatActivity() {    override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
  • Added a Button in an Android app using the Layout Editor.
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/roll"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />
  • Modified the MainActivity.kt class to add interactive behavior to the app.
val rollButton: Button = findViewById(R.id.button)
rollButton.setOnClickListener {
// code here
}
  • Popped up a Toast message as a temporary solution to verify that we’re on the right track.
val toast = Toast.makeText(this, "Dice Rolled!", Toast.LENGTH_SHORT)
toast.show()
// Or you could combine the two lines in the click listener into a single line without a variable.
Toast.makeText(this, "Dice Rolled!", Toast.LENGTH_SHORT).show()
  • Set up an on-click listener for a Button using setOnClickListener() to add behavior for when a Button is clicked.
rollButton.setOnClickListener {
val resultTextView: TextView = findViewById(R.id.textView)
resultTextView.text = "6"
}
class Dice(val numSides: Int) { fun roll(): Int {
return (1..numSides).random()
}
}
rollButton.setOnClickListener { rollDice() }
/**
* Roll the dice and update the screen with the result.
*/
private fun rollDice() {
// Create new Dice object with 6 sides and roll it
val dice = Dice(6)
val diceRoll = dice.roll()
// Update the screen with the dice roll
val resultTextView: TextView = findViewById(R.id.textView)
resultTextView.text = diceRoll.toString()
}
  • When the app is running, we can update the screen by calling methods on the TextView, Button, or other UI elements in the layout.
  • Comment out our code to help other people who are reading our code to understand what our approach was.

That is all for Day35 ✅

Thanks for reading, See you tomorrow!

--

--

Kushagra Kesav
Kushagra Kesav

Written by Kushagra Kesav

Developer Relations | Communities | Software Engineering | https://www.linkedin.com/in/kushagrakesav

No responses yet