Issue
I'm trying to catch the onClick event from a button inside a fragment but it's not working.
Any tip?
I have this main activity and I call the fragment throught a 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)
}
}
The activity_main.xml is the container of the linearLayout which will cointain the fragment.
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"
/>
My fragment is simple it just have a button and i want to catch the onClickEvent from this button
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()
}
}
}
Solution
You're returning before you can setup the listener here:
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
}
Try like this:
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
}
Answered By - Levi Moreira
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.