Search code examples
androidxmlkotlin

Change drawable property of ImageView


I'm trying to make a button in my app which changes the wallpaper of it (not the wallpaper on the phone, but the app's wallpaper). But I can't for the life of me figure out how to do it, nor can I find anything about it.

lateinit var backgroundimg : ImageView
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    backgroundimg = findViewById<ImageView>(R.id.background)

}
fun change_wallpaper() {
    var wallpapers = arrayOf(wallpapers here)
    var choice = (0..wallpapers.size).random()
    var chosenwallpaper = wallpapers[choice]

    // DONT KNOW WHAT TO DO HERE
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="centerCrop"
        android:src="@drawable/[CHANGE THIS PROPERTY]"
        android:id="@+id/background">
    </ImageView>

    <ImageButton
        android:layout_width="10mm"
        android:layout_height="10mm"
        android:layout_marginTop="100mm"
        android:layout_marginLeft="51mm"
        android:background="@drawable/xmlasset_reloadbutton"
        android:id="@+id/reload_wallpaper"/>

</RelativeLayout>

I've mostly just googled around to see if I can find anything, but as I said I couldn't.


Solution

  • lateinit var backgroundimg : ImageView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        backgroundimg = findViewById<ImageView>(R.id.background)
    
    }
    fun change_wallpaper() {
        var wallpapers = arrayOf(wallpapers here)
        var choice = (0..wallpapers.size).random()
        var chosenwallpaper = wallpapers[choice]
    
        // DONT KNOW WHAT TO DO HERE
        //if image is bitmap
        backgroundimg.setImageBitmap(chosenwallpaper)
        //if image is drawable
        backgroundimg.setImageDrawable(chosenwallpaper)
    
    }