我尝试从片段中的按钮捕获onClick事件,但没有成功。
有小费吗?
我有一个主活动,我通过bottomNavigation.MainActivity.kt调用这个片段:
class MainActivity : FragmentActivity() {
private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
showFragmentSetup()
return@OnNavigationItemSelectedListener true
}
}
false
}
fun showFragmentSetup(){
val setupFragment = SetupFragment()
val manager = supportFragmentManager
val transaction = manager.beginTransaction()
transaction.replace(R.id.setupFragment, setupFragment)
transaction.addToBackStack(null)
transaction.commit()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
}
}
activity_main.xml是将包含片段的linearLayout的容器。
activity_main.xml
<LinearLayout
android:id="@+id/setupFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
/>
我的片段很简单,它只有一个按钮,我想从这个按钮捕获onClickEvent
class SetupFragment : Fragment(){
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_setup, container, false)
val view: View = inflater!!.inflate(R.layout.fragment_setup, container, false)
btnSetup.setOnClickListener { view ->
Log.d("btnSetup", "Selected")
}
// Return the fragment view/layout
return view
}
companion object {
fun newInstance(): SetupFragment {
return SetupFragment()
}
}
}
4条答案
按热度按时间gmol16391#
您返回的是可以在此处设置侦听器之前的状态:
试着这样做:
rhfm7lfc2#
我认为您应该在“SetupFragment”中使用“onViewCreated”函数
jtjikinw3#
您没有为该按钮提供视图
h43kikqp4#
这是在片段中设置View. Oclicklistener接口后如何在viewBinding中进行操作
覆盖创建视图上的功能(inflater:布局充气机,容器:视图组?,已保存示例状态:捆绑包?):查看{