我正在尝试从片段中的按钮捕获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()
}
}
}
答案 0 :(得分:8)
您要返回,然后才能在此处设置侦听器:
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
}
尝试这样:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view: View = inflater!!.inflate(R.layout.fragment_setup, container, false)
view.btnSetup.setOnClickListener { view ->
Log.d("btnSetup", "Selected")
}
// Return the fragment view/layout
return view
}
答案 1 :(得分:2)
您没有为该按钮提供视图
lateinit var mView: View
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
mView=inflater.inflate(R.layout.product_list,container,false)
mView.addProduct.setOnClickListener {
val intent=Intent(activity,ProductAddActivity::class.java)
startActivity(intent)
}
return mView
}
答案 2 :(得分:0)
我认为您应该在“ SetupFragment”中使用“ onViewCreated”功能
pref2