【问题标题】:How to do I navigate to a fragment when I click on a cardview当我点击卡片视图时如何导航到片段
【发布时间】:2022-01-20 05:53:48
【问题描述】:

我正在练习 Kotlin,当我点击 cardView 时,我试图导航到一个片段。

请耐心和理解我是新人,因为我什至不知道如何问这个问题,即使我知道我想做什么..

我想我需要创建一个这样的函数:

private fun CardView.setOnClickListener(function: () -> Unit) {

}

但我不知道我会通过什么论据。 这是我希望能够点击的两个 CardView:

<androidx.cardview.widget.CardView
    android:id="@+id/ways_teach_people_what_you_know"
    android:layout_width="250dp"
    android:layout_height="350dp"
    app:cardElevation="8dp"
    app:cardCornerRadius="12dp"
    android:layout_marginTop="50dp"
    android:layout_margin="30dp"
    android:layout_rowWeight="1"
    android:layout_columnWeight="1"
    android:clickable="true"
    android:focusable="true">

<androidx.cardview.widget.CardView
    android:id="@+id/ways_show_people_how_to_do_things"
    android:layout_width="250dp"
    android:layout_height="350dp"
    app:cardElevation="6dp"
    app:cardCornerRadius="12dp"
    android:layout_margin="30dp"
    android:layout_rowWeight="1"
    android:layout_columnWeight="1"
    android:clickable="true"
    android:focusable="true">

并且想要将那些cardViews导航到这些片段;

import androidx.fragment.app.Fragment

class WaysTeachPeopleWhatYouKnowFragment : Fragment(R.layout.fragment_ways_teach_people_what_you_know) {

}


import androidx.fragment.app.Fragment

class WaysShowPeopleHowToDoThingsFragment : Fragment(R.layout.fragment_ways_show_people_how_to_do_things) {

}

我没有添加我想要导航到的片段的.xml文件,它现在是空的,但是如果你需要它,我可以添加它。

请在引用 CardView 时使用findViewByID

如果我不需要创建一个函数,或者您知道另一个我可以在单击 cardView 时导航到片段,我很乐意学习它。

我很感激一些示例代码,请让我更容易理解和理解,以便我可以添加其他我想导航到的 cardView 和片段。感谢您提前提供帮助。

【问题讨论】:

    标签: android android-studio kotlin android-fragments android-cardview


    【解决方案1】:

    如果你使用的是 navController 那么 活动中

    CardView.setOnClickListener{
    

    findNavController(R.id.nav_host_fragment).navigate(R.id.your_destination_fragment)}

    在片段中

    CardView.setOnClickListener{
    

    findNavController().navigate(R.id.your_destination_fragment)}

    【讨论】:

      【解决方案2】:

      我对应用程序做了很多改动,看看这个video,它对我有帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-05
        • 2021-11-29
        • 1970-01-01
        相关资源
        最近更新 更多