Home > Software engineering >  Difference between storing an imageview in a variable and intializing it later, compared to doing it
Difference between storing an imageview in a variable and intializing it later, compared to doing it

Time:04-10

I am new to android studio development, I am trying to figure out what makes these two codes below different. The code line that needs help is indicated with <----

class MainActivity : AppCompatActivity() {
 lateinit var diceImage: ImageView  <----

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val rollButton: Button = findViewById(R.id.roll_button)
    rollButton.setOnClickListener {
        rollDice()
    }

    diceImage = findViewById(R.id.dice_image) <----
}

Compared to just declaring and initializing the variable

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val rollButton: Button = findViewById(R.id.roll_button)
    rollButton.setOnClickListener {
        rollDice()
    }

    val diceImage: ImageView = findViewById(R.id.dice_image)<----
}

I was following a tutorial and I was wondering what the difference was, thanks!

CodePudding user response:

The difference between these two

diceImage = findViewById(R.id.dice_image)<ImageView>{}

val diceImage: ImageView = findViewById(R.id.dice_image)

is just the declaration. The second line decalared:

val diceImage: ImageView = findViewById(R.id.dice_image)

because by defining diceImage as a variable with the shortcut : and adding Imageview component then you don't have add the ImageView at the end of the declaration like the first line. It's just a short way of declaring findViewByID on android.

  • Related