简体   繁体   中英

What is the best way to declare a bunch of drawables (Kotlin)?

I have a lot of vector icons as XML drawable resources (96 to be exact). I display them in 8 categories. Currently i declared them as follows:

private val categoryA = arrayListOf(R.drawable.a1, ... R.drawable.an)
private val categoryB = arrayListOf(R.drawable.b1, ... R.drawable.bn)
***
private val categoryH = arrayListOf(R.drawable.h1, ... R.drawable.hn)

Everything works fine and fast, but i am not sure if that is a good way for a real app. I also use Room DB for other purposes in the app, so should i add new table and prepopulate DB on first launch? It is also easy, at least right now, to add/remove icons later on... But on the other hand the code does not look nice (to me) with so many R.drawable.id lines.

Write a function that can get your drawable Ints by reflection:

fun getDrawableIdByName(name: String) = try {
    R.drawable::class.java.getField(name).getInt(null)
} catch (e: NoSuchFieldException) {
    error("No drawable with name $name")
}

Then you can construct your lists with it:

val categoryLists = ('a'..'h')
    .map { category ->
        List(12) { index ->
            getDrawableIdByName("$category${index + 1}")
        }
    }

I suppose you could write this to your database after the first launch, but I think it's overkill for only 96 items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM