I know I can use an id
attribute with Anko to identify a view:
class MainActivityUI : AnkoComponent<MainActivity> {
override fun createView(ui: AnkoContext<MainActivity>) = with(ui) {
frameLayout {
textView {
id = R.id.text
}
}
}
}
Then obtain it in the Activity
using the find()
function (or by using Kotlin Android Extensions):
class MainActivity : AppCompatActivity() {
private val textView by lazy {
find<TextView>(R.id.text)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
MainActivityUI().setContentView(this)
textView.text = "Hello World"
}
}
But I feel like I am missing something; the only place the README mentions the find
function or Kotlin Android Extensions is in the section titled Supporting Existing Code:
You don't have to rewrite all your UI with Anko. You can keep your old classes written in Java. Moreover, if you still want (or have) to write a Kotlin activity class and inflate an XML layout for some reason, you can use View properties, which would make things easier:
// Same as findViewById(), simpler to use val name = find<TextView>(R.id.name) name.hint = "Enter your name" name.onClick { /*do something*/ }
You can make your code even more compact by using Kotlin Android Extensions.
Which makes it seem like the find
function is only meant for supporting "old" XML code.
So my question is this; is using an id
along with the find
function the correct way of accessing a View
from the Activity
using Anko? Is there a more "Anko" way of handling this? Or am I missing some other benefit of Anko that makes accessing the View
from the Activity
irrelevant?
And a second related question; if this is the correct way of accessing a View
from the Activity
, is there a way of creating an id
resource (i.e. "@+id/"
) from within an AnkoComponent
? Rather than creating each id
in the ids.xml
file.
<include>
tag in XML), from what I understand, you must create a separateAnkoComponent
, and use it as a view in the other component. In this case, eachView
member would be attached to the component it resides within; instead of the entire view. In this case, you would have to use saymainUI.toolbarUI.toolbar
to access a reused view; whereasfind()
can access any view within the hierarchy. β Ment