Is it weird to get a context reference from a view...
# getting-started
s
Is it weird to get a context reference from a view, for something slightly unrelated? For something like this, where
z
is a textView:
Copy code
z.text = z.context.getString(R.string.empty)
t
This is perfectly fine as long as you dont keep a reference to the
Context
that outlives the `Fragment`/`Activity` where the
View
is defined (this would result in memory leaks). Note that in your sample code, you could have used
z.setText(R.string.empty)
, which internally does what your code is doing : accessing resources from its Context.
a
I'm struggling to think of a scenario where you would need to reference context this way. Like @tseisel said setText would get context on its own, but even that is un-necessary in Kotlin, it can and arguably should be set more explicitly using the '=' operator. For example:
Copy code
z.text = resources.getString(R.string.empty)
or
Copy code
z.text = ""
s
@Alex Crafford Here is the function for context. I was thinking I could eliminate the
context
parameter:
Copy code
fun replaceEmptyDataWithLiteralEmptyStringIfNeeded(c: Context, textViews: List<TextView>, data: List<String?>) {

    (textViews zip data).forEach { z ->

        if (!z.second.isNullOrEmpty()) {
            z.first.text = z.second
            z.first.setTypeface(null, Typeface.NORMAL)
        } else {
            z.first.text = c.getString(R.string.empty)
            z.first.setTypeface(null, Typeface.ITALIC)
        }
    }
}
a
I think I would eliminate the context param, and use a string literal there as long as it will always be an empty string.
s
It will not always be an empty string, sometimes I will have to
getString
. Ah- that empty string is literally the word “empty” 😅
a
Oh ok, can that be set as the default text for the field?
s
It looks a little off in the UI as the the text is fetched over the network (the flash of “empty” has been deemed undesirable)
a
Yeah that makes sense. Is this method inside of the parent fragment/activity or is it outside of that context entirely?
If this is in a ViewModel and not a Activity/Fragment, its probably best to not use context at all but rather change that param from Context to String which is passed from the view using. This way you don't risk memory leaks
s
Ah yes makes sense - thanks 😃