Android Fragments onClick搭配RelativeLayout无法在片段中运作

0x6upsns  于 2022-11-24  发布在  Android
关注(0)|答案(1)|浏览(132)

我正在学习编写Android应用程序,但我遇到了这个问题。onClick没有做任何事情,我不知道可能是问题所在。请帮助

HomeFragment.kt
class HomeFragment:Fragment(com.advmusic.R.layout.fragment_home) {
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        val smh : View =  inflater.inflate(R.layout.fragment_home, container, false)
        val recently_played_1 : RelativeLayout = smh.findViewById(R.id.recently_played_1)
        recently_played_1.setClickable(true)

        recently_played_1.setOnClickListener { Toast.makeText(activity, "This is my Toast  message!", Toast.LENGTH_LONG).show() }

fragment_home.xml
<RelativeLayout
                        android:layout_width="250dp"
                        android:layout_height="match_parent"
                        android:background="@drawable/recently_played_shape"
                        android:id="@+id/recently_played_1"
                        android:paddingStart="10dp"
                        android:layout_marginEnd="15dp">
7xllpg7q

7xllpg7q1#

我没有在HomeFragment.kt中使用它,而是在MainActivity.kt中的fragmentcreate上编写了这个代码
when(它的项目ID){

R.id.bottom_nav_home_button-> {
                val view = findViewById<View>(R.id.main_fragment_container) as FrameLayout
                val smh = layoutInflater.inflate(R.layout.fragment_home, view)
                val recently_played_title = smh.findViewById(R.id.recently_played_title) as RelativeLayout

                recently_played_title.setOnClickListener {
                    Toast.makeText(this, "This is my Toast message!", Toast.LENGTH_LONG).show()

}}

相关问题