View Binding 在 v3.6 中发布。
Docs:
https://developer.android.com/topic/libraries/view-binding https://developer.android.com/topic/libraries/view-binding
我的问题是,有谁知道如何使用包含布局的视图绑定?
给定的布局包含另一个布局
<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>
我正在尝试引用 item_header 布局内的项目。
binder.my_header (<-- this just returns back the view)
binder.root (<-- this just returns back the root view)
即使我将 id 添加到 item_header 的根,例如 id="@+id/parent_id" 并尝试引用它,我也会收到空指针异常
binder.parentId (<-- I have access to views inside of the item_header, however, I receive exceptions. Says that "parentId" cannot be found)
如何参考布局,item_header
?
假设您问题中的布局是activity_main.xml
。为其生成的视图绑定类是ActivityMainBinding
。同样,对于item_header.xml
,生成的视图绑定是ItemHeaderBinding
.
如果我们假装那样item_header.xml
has a TextView
named @+id/foo
,那么你最终会得到这块 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
对象应该有一个属性android:id
你给的<include>
— myHeader
在这种情况下。那应该是一个ItemHeaderBinding
,因为视图绑定似乎为设置嵌套绑定对象<include>
. Since myHeader
is an ItemHeaderBinding
,然后您可以引用其上的小部件,就像直接充气一样ItemHeaderBinding
你自己。
请注意,视图绑定似乎会转换lower_snake_case
into lowerCamelCase
, 所以my_header
ID 变成myHeader
就生成的代码而言。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)