簡體   English   中英

單擊卡片視圖時如何導航到片段

[英]How to do I navigate to a fragment when I click on a cardview

我正在練習 Kotlin,我試圖在單擊cardView時導航到片段。

請表現出一些耐心和理解我是新來的,因為我什至不知道怎么問這個,即使我知道我想做什么..

我想我需要像這樣創建一個 function:

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">

並希望將這些 cardView 導航到這些片段;

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

如果我不需要創建 function,或者你知道另一個我可以在單擊 cardView 時導航到片段,我非常樂意學習它。

我會很感激一些示例代碼,請讓我更容易理解和理解,以便我可以添加我想要導航到的其他 cardView 和片段。感謝您提前提供幫助。

我對應用程序進行了很多更改,觀看此視頻,它對我有所幫助。

如果您使用的是 navController 然后在 Activity

CardView.setOnClickListener{

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

在片段中

CardView.setOnClickListener{

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM