我有一个Expected 0 to Equal 1
和一个MainActivity
和一个ViewPager2
。在这个FragmentStateAdapter
中,我有5个ViewPager
具有不同的布局。我正在尝试在所说的Fragments
上实现一些EditTexts
和Buttons
。但是,没有任何侦听器触发器。
在调试时,将执行onCreate中的所有代码,但永远不会触发监听器。
这是我的片段:
Fragments
这是我的ViewPager适配器:
class SearchFragment : Fragment() {
private lateinit var searchBinding: FragmentSearchBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
searchBinding = FragmentSearchBinding.inflate(layoutInflater)
var test = activity?.findViewById<TabLayout>(R.id.tab_layout)
searchBinding.testButton.setOnClickListener{
v -> Toast.makeText(context,"This is a test",Toast.LENGTH_SHORT).show()
}
searchBinding.searchBar.setOnFocusChangeListener{view, hasFocus ->
if (hasFocus){
if (test != null) {
test.isVisible = false
}
Log.d("SearchFragment", "onFocus")
}else{
if (test != null) {
test.isVisible = true
}
}
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_search, container, false)
}
override fun onClick(v: View) {
when (v.id) {
R.id.search_bar -> {
Toast.makeText(v.context, "This is a test", Toast.LENGTH_SHORT)
}
}
}
}
答案 0 :(得分:0)
我认为您需要阅读有关Fragments生命周期的信息。处理视图的生命周期部分在onCreateView
和onDestroyView
之间。 onCreate
在此之前发生。 Check out the guide from Android。
此外,我对ViewBinding的使用经验也不多,但我认为您的做法不正确。
根据documentation,您应该按照以下方式进行操作:
class SearchFragment : Fragment() {
private var _binding: FragmentSearchBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val searchBinding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentSearchBinding.inflate(inflater, container, false)
val view = searchBinding.root
var test = activity?.findViewById<TabLayout>(R.id.tab_layout)
searchBinding.testButton.setOnClickListener{
v -> Toast.makeText(context,"This is a test",Toast.LENGTH_SHORT).show()
}
searchBinding.searchBar.setOnFocusChangeListener{view, hasFocus ->
if (hasFocus){
if (test != null) {
test.isVisible = false
}
Log.d("SearchFragment", "onFocus")
}else{
if (test != null) {
test.isVisible = true
}
}
}
return view
}
override fun onDestroyView() {
_binding = null
}
}