I am new to Android development. I'm doing it with Kotlin. I got an assignment to change the imageView image using OnLongClickListener like changing two to three images every long press. also, I want to save the state of the images after the rotating screen. I set it up for changing one image to another for one time but still confused how to do it properly.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
lightMe.setOnLongClickListener {
lightMe.run {
lightMe.setImageDrawable(getDrawable(R.drawable.ic_baseline_flare_24))
lightMe.setImageDrawable(getDrawable(R.drawable.ic_baseline_wb_incandescent_24))
true
}
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
}
Check this example. I have added one ImageView
and I am changing the image on a long click.
MainActivity.kt:
import android.os.Bundle
import android.util.Log
import androidx.annotation.DrawableRes
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
companion object {
const val IMAGE_ID_KEY = "IMAGE_ID_KEY" //key to save imageId
}
@DrawableRes
private var imageId = R.drawable.ic_launcher_foreground //field which keeps actual drawable id
set(value) {
field = value
image.setImageResource(value) //every time value is changed, ImageView is updated
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d("MY_TAG", "onCreate")
image.setOnLongClickListener {
Log.d("MY_TAG", "longClick")
// change image to the opposite
imageId =
if (imageId == R.drawable.ic_launcher_background) R.drawable.ic_launcher_foreground else R.drawable.ic_launcher_background
true
}
}
// saving imageId before app can be destroyed. E.g. rotation
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
Log.d("MY_TAG", "onSaveInstanceState")
outState.putInt(IMAGE_ID_KEY, imageId)
}
// restoring imageId every time app is recreating
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
Log.d("MY_TAG", "onRestoreInstanceState")
imageId = savedInstanceState.getInt(IMAGE_ID_KEY)
}
}
main_activity.xml (just an image):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:src="@drawable/ic_launcher_foreground"
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>