How to use View Binding with Included Views?

portfoliobuilder :

View Binding got released with v3.6.

Docs: https://developer.android.com/topic/libraries/view-binding

My question is, does anyone know how to use view binding with included layouts?

Given Layout that includes another Layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include
        android:id="@+id/my_header"
        layout="@layout/item_header"
        android:layout_width="match_parent"
        android:layout_height="100dp" />

</LinearLayout>

I am trying to reference items inside of the item_header layout.

binder.my_header (<-- this just returns back the view)
binder.root (<-- this just returns back the root view)

Even if I add an id to the root of the item_header, such as id="@+id/parent_id" and try to reference that, I receive null pointer exceptions

binder.parentId (<-- I have access to views inside of the item_header, however, I receive exceptions. Says that "parentId" cannot be found)

How to reference the layout, item_header?

CommonsWare :

Let's suppose that the layout in your question is activity_main.xml. The generated view binding class for it is ActivityMainBinding. Similarly, for item_header.xml, the generated view binding is ItemHeaderBinding.

If we pretend that item_header.xml has a TextView named @+id/foo, then you wind up with this chunk of Kotlin:

class MainActivity : AppCompatActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    val mainBinding = ActivityMainBinding.inflate(layoutInflater)

    setContentView(mainBinding.root)

    mainBinding.myHeader.foo.text = "this is a test"
  }
}

So, the ActivityMainBinding object should have a property with the android:id that you gave to the <include>myHeader in this case. That should be an ItemHeaderBinding, as view binding appears to set up the nested binding object for the <include>. Since myHeader is an ItemHeaderBinding, you can then reference widgets on it just as you would if you directly inflated ItemHeaderBinding yourself.

Note that view binding appears to convert lower_snake_case into lowerCamelCase, so the my_header ID turns into myHeader in terms of the generated code.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=175276&siteId=1