I want to retrieve the id of a Layout inside of one of my layout xmls, and it's possible to use both R.id.* and the binding for this - details below. Which is the preferred way?
Given the following structure:
app
|-- java.org.romco.appname
| |-- MainActivity.kt
|-- res.layout
| |-- main_activity.xml
| |-- main_content.xml
Let's say my main_activity.xml is a CoordinatorLayout and includes the main_content.xml with a defined id of "main_content", such as:
android:id="@+id/main_content"
layout="@layout/content_main" />
My content_main.xml then contains a FrameLayout with a defined if of "task_details_container", such as:
<FrameLayout
android:id="@+id/task_details_container" />
Following the official guides, the binding in MainActivity.kt would be created as:
class MainActivity : AppCompatActivity() {
private lateinit var mainActivityBinding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mainActivityBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(mainActivityBinding.root)
}
If I now want to refer to the FrameView inside of my content_main.xml, how do I go about it? Should i use what I'd normally use, so R.id.task_details_container, or is it preferred to use the binding to retrieve the ID now that I have it available? If I try to log it in onCreate, the output is the same:
val id1 = R.id.task_details_container
val id2 = mainActivityBinding.mainContent.taskDetailsContainer.id
Log.d("MainActivity", "R id = $id1, binding id = $id2")
Log output:
D/MainActivity: R id = 2131231072, binding id = 2131231072
From what I've found so far:
here's a video where they introduce view binding, but they only mention it as a way to avoid using findViewById: https://www.youtube.com/watch?v=td3Kd7fOROw&t=1756s
This article walks us through using view binding, in both activities and fragments, but again, seemingly only as a way to avoid findViewById. https://medium.com/androiddevelopers/use-view-binding-to-replace-findviewbyid-c83942471fc
The official doc covers pretty much the same as the article: https://developer.android.com/topic/libraries/view-binding
But none of these talk about whether using the bound id is better than using R.id.. My guess is that using R.id. is preferred, since not all elements have to be view-bound and therefore, for the sake of consistency, I can use R.id.* everywhere, where as I possibly can't use binding where the property is not accessible. But as I said, it's just a guess and I'd like to hear a wiser opinion on this.