gpt4 book ai didi

android - 如何将 与 View 绑定(bind)一起使用?

转载 作者:行者123 更新时间:2023-12-03 14:48:05 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How can I access views from layout containing merge tag is included in another layout?

(2 个回答)


去年关闭。




我无法获得带有合并根标记的布局来处理 View 绑定(bind)。可能吗?

include_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<include
android:id="@+id/include_test"
layout="@layout/merge_layout"/>
</FrameLayout>

合并布局.xml:
<?xml version="1.0" encoding="utf-8"?>
<merge
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/include_test">

<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="A Title"/>
</merge>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = IncludeLayoutBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.includeTest.title.text = "New Title"
}

运行时异常: java.lang.NullPointerException: Missing required view with ID: includeTest

最佳答案

基于 this article这是可能的
例如 :
my_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
layout="@layout/my_include_layout"/>
</LinearLayout>
my_include_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<merge
xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</merge>
我的 fragment .kt
class MyFragment: Fragment() {
private val binding: MyFragmentBinding get() = _binding!!
private var _binding: MyFragmentBinding? = null
private val myIncludeLayoutBinding: MyIncludeLayoutBinding get() = _myIncludeLayoutBinding!!
private var _myIncludeLayoutBinding: MyIncludeLayoutBinding? = null

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = MyFragmentBinding.inflate(inflater, container, false)
_myIncludeLayoutBinding = MyIncludeLayoutBinding.bind(binding.root)
return binding.root
}

override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
myIncludeLayoutBinding.button.setOnClickListener{

}
}

override fun onDestroyView() {
super.onDestroyView()
_binding = null
_myIncludeLayoutBinding = null
}
}

关于android - 如何将 <merge> 与 View 绑定(bind)一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59748866/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com