如何在片段中实现OnClick和OnFocusChanged侦听器

时间:2020-03-22 09:14:54

标签: android android-fragments kotlin

我有一个Expected 0 to Equal 1和一个MainActivity和一个ViewPager2。在这个FragmentStateAdapter中,我有5个ViewPager具有不同的布局。我正在尝试在所说的Fragments上实现一些EditTextsButtons。但是,没有任何侦听器触发器。 在调试时,将执行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)
        }
    }
}

}

1 个答案:

答案 0 :(得分:0)

我认为您需要阅读有关Fragments生命周期的信息。处理视图的生命周期部分在onCreateViewonDestroyView之间。 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
  }

}