Home > Enterprise >  How to navigate from specific selected item RecyclerView Inside the Fragment, to 2 different Activit
How to navigate from specific selected item RecyclerView Inside the Fragment, to 2 different Activit

Time:07-23

How to navigate from specific selested item RecyclerView Inside the Fragment, to 2 different Activity in Kotlin?

Basic Layout Wireframe, and guide of what I want to ask

i have the basic wireframe layout, who describe my question, because i don't know how to explain with good typing.

so here from the wireframe, i have 1 Activity with TabLayout, which is filled with Fragment and there is a RecyclerView in it. And then I have 2 more different Activities. for now, i've successfully implemented data parsing to "OtherActivity1" from RecyclerView inside the fragment TabLayout on MainActivity.

But now, i need to open "OtherActivity2" from the same RecyclerView on Main Activity, what i mean here is specifically only from "RecyclerView Item4" and without data parsing.

How To Doing That?

Anyone have a tutorial?, because i can't find any tutorials like on youtube for this case.

and this my sample code ( not exactly the same, but describing the same meaning) :

MainActivity.kt

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        setUpTabs() // Assign TabLayout

    } // End - OnCreate


    // Start - TabLayout
    private fun setUpTabs() {
        val adapter = ViewPagerAdapter(supportFragmentManager)
        adapter.addFragment(TAB1Fragment(), "TAB1")
        adapter.addFragment(TAB2Fragment(), "TAB2")
        adapter.addFragment(TAB3Fragment(), "TAB3")
        viewPager_tabLayout.adapter = adapter
        tabs.setupWithViewPager(viewPager_tabLayout)
    } // End - TabLayout

} // End Class

TAB1Fragment.kt

    class TAB1Fragment : Fragment() {
    
        lateinit var tab1Adapter: TAB1Adapter // Initialize Adapter
        private val sLM = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL) // Initialize LayoutManager
        val addTAB1ModelList: MutableList<TAB1Model> = ArrayList() // Initialize ListModel
    
    
        override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            return inflater.inflate(R.layout.fragment_tab1, container, false)
        } // End onCreateView
    
        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
    
            initViewTAB1() // Assign ListModel putExtras
            actionTAB1() // Assign Action putExtras
    
        } // End - OnViewCreated
    
    
        // Start - ListModel putExtras
        fun initViewTAB1() { 
    
            rv_tab1.layoutManager = sLM
            rv_tab1.setHasFixedSize(true)
            tab1Adapter = TAB1Adapter(requireActivity())
            rv_tab1.adapter = tab1Adapter
    
            addTAB1ModelList.add(TAB1Model("RecyclerView Item1", "Desc RecyclerView Item1", R.drawable.cv1))
            addTAB1ModelList.add(TAB1Model("RecyclerView Item2", "Desc RecyclerView Item1", R.drawable.cv2))
            addTAB1ModelList.add(TAB1Model("RecyclerView Item3", "Desc RecyclerView Item1", R.drawable.cv3))
            addTAB1ModelList.add(TAB1Model("RecyclerView Item4", "Desc RecyclerView Item1", R.drawable.cv4))
         
            tab1Adapter.setTAB1(addTAB1ModelList)
        }
        // End - ListModel putExtras
    
    
        // Start - Action putExtras
        fun actionTAB1() {
    
            tab1Adapter.setOnClickItemListenerTAB1(object : OnItemClickListener {
                override fun onItemClick(item: View, position: Int) {
                    var i = Intent(context, OtherActivity1::class.java)
                    i.putExtra("prodNameTAB1", tab1Adapter.getTAB1().get(position).getProdNameTAB1())
                    i.putExtra("prodPriceTAB1", tab1Adapter.getTAB1().get(position).getProdPriceTAB1())
                    i.putExtra("prodImgTAB1", tab1Adapter.getTAB1().get(position).getProdImgTAB1())
                    startActivity(i)
                }
            }) 
            // End - Action putExtras
    
    
        } // End - Class

TAB1Model.kt

class TAB1Model  {

private var prodNameTAB1: String // Initialize prodNameTAB1
private var prodPriceTAB1: String // Initialize prodPriceTAB1
private var prodImgTAB1: Int // Initialize prodImgTAB1

constructor (prodNameTAB1: String, prodPriceTAB1: String, prodImgTAB1: Int) {
    this.prodNameTAB1 = prodNameTAB1 // Assign prodNameTAB1
    this.prodPriceTAB1 = prodPriceTAB1 // Assign prodPriceTAB1
    this.prodImgTAB1 = prodImgTAB1 // Assign prodImgTAB1
}

// Start - ProdNameTAB1
fun getProdNameTAB1(): String {
    return prodNameTAB1
}

fun setProdNameTAB1(prodNameTAB1: String) {
    this.prodNameTAB1 = prodNameTAB1
}
// End - ProdNameTAB1

// Start - prodPriceTAB1
fun getProdPriceTAB1(): String {
    return prodPriceTAB1
}

fun setProdPriceTAB1(prodPriceTAB1: String) {
    this.prodPriceTAB1 = prodPriceTAB1
}
// End - prodPriceTAB1

// Start - prodImgTAB1
fun getProdImgTAB1(): Int {
    return prodImgTAB1
    }

fun setprodImgTAB1(prodImgTAB1: Int) {
    this.prodImgTAB1 = prodImgTAB1
    }
// End - prodImgTAB1


} // End Class

TAB1Adapter.kt

class TAB1Adapter(private val context: Context) : RecyclerView.Adapter<TAB1Adapter.TAB1ViewHolder>() {

    private val tab1Model: MutableList<TAB1Model> = mutableListOf() // Initialize tab1Model
    private lateinit var onSelectedListenerTAB1: OnItemClickListener // Initialize tab1Listener

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TAB1ViewHolder {
        return TAB1ViewHolder(LayoutInflater.from(context).inflate(R.layout.item_tab1_layout, parent, false))
    } //End - onCreateViewHolder

    override fun getItemCount(): Int {
        return tab1Model.size
    } // End - getItem

    override fun onBindViewHolder(holder: TAB1ViewHolder, position: Int) {
        holder.tab1BindView(tab1Model[position])
    } //End - onBindViewHolder


    //Start - setTAB1Model
    fun setTAB1(data: List<TAB1Model>) {
        tab1Model.clear()
        tab1Model.addAll(data)
        notifyDataSetChanged()
    } 
    //End - setTAB1Model


    // Start - getTAB1Model
    fun getTAB1(): MutableList<TAB1Model> {
        return tab1Model
    } 
    // End - getTAB1Model

    
    // Start - TAB1ViewHolder
    inner class TAB1ViewHolder(tab1view: View) : RecyclerView.ViewHolder(tab1view) {
        val imgProdTAB1 = tab1view.findViewById<ImageView>(R.id.iv_prodTAB1)
        val cvTAB1: MaterialCardView = tab1view.findViewById(R.id.cv_tab1)

        fun tab1BindView(tab1Model: TAB1Model) {
            imgProdTAB1.setImageResource(tab1Model.getProdImgTAB1())
    }

          init {
              cvTAB1.setOnClickListener { onSelectedListenerTAB1.onItemClick(it, layoutPosition) }
         }

    } 
    // End - TAB1ViewHolder

    // Start - setOnClickItemListenerTAB1
    fun setOnClickItemListenerTAB1(onItemClickListener: OnItemClickListener) {
        this.onSelectedListenerTAB1 = onItemClickListener
    } 
    // End - setOnClickItemListenerTAB1

OtherActiviy1.kt

class OtherAtivity1 : AppCompatActivity() {

    var prodBundle : Bundle? = null // Initialize Bundle
   
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_other1)


        initView() // Assign Extras Reciver

    } // End - OnCreate

    
    // Start - Extras Reciver
    fun initView() {
        prodBundle = intent.extras

        phtv_ProdName.text = prodBundle?.getString( "prodNameTAB1" )
        phtv_ProdPrice.text = prodBundle?.getString( "prodPriceTAB1" )
        prodBundle?.getInt("prodImgTAB1")?.let { ph_ivProd.setImageResource(it) }
    } 
    // End - Extras Reciver


} // End - Class

OtherActiviy2.kt

class OtherAtivity2 : AppCompatActivity() {

   
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_other2)


    } // End - OnCreate



} // End - Class

OnItemClickListener.kt

interface OnItemClickListener {
    fun onItemClick(item: View, position:Int)
}

I hope someone help me solve this problem. Thank you so much for taking your time to help me. :)

CodePudding user response:

You get the position in OnItemClickListener callback and can check the position if it's 3 then intent to OtherActivity2

tab1Adapter.setOnClickItemListenerTAB1(
    object : OnItemClickListener {
        override fun onItemClick(item: View, position: Int) {
            if (position == 3) {
                var i = Intent(context, OtherActivity2::class.java)
            } else {
                var i = Intent(context, OtherActivity1::class.java)
            }
            i.putExtra("prodNameTAB1", tab1Adapter.getTAB1().get(position).getProdNameTAB1())
            i.putExtra("prodPriceTAB1", tab1Adapter.getTAB1().get(position).getProdPriceTAB1())
            i.putExtra("prodImgTAB1", tab1Adapter.getTAB1().get(position).getProdImgTAB1())
            startActivity(i)
        }
    }
)

CodePudding user response:

Specifically to answer your question this will work, When position is 4 the user clicked the 4 item.

             override fun onItemClick(item: View, position: Int) {
                if(position == 4){
                    var i = Intent(context, OtherActivity2::class.java)
                    startActivity(i)
                }else{
                    var i = Intent(context, OtherActivity1::class.java)
                    i.putExtra("prodNameTAB1", tab1Adapter.getTAB1().get(position).getProdNameTAB1())
                    i.putExtra("prodPriceTAB1", tab1Adapter.getTAB1().get(position).getProdPriceTAB1())
                    i.putExtra("prodImgTAB1", tab1Adapter.getTAB1().get(position).getProdImgTAB1())
                    startActivity(i)
                }
            }

Now in reality this is not exactly a good idea. You don't want to base logic on positions when the position doesn't really matter, its what is at that position that matters.

1st change your interface so that you are receiving the "data" that was clicked.

interface OnItemClickListener {
    fun onItemClick(item: TAB1Model)
}

2nd to get this to work you will set the model when it is bound to the viewholder.

    var tab1Model : TAB1Model? = null
    
    fun tab1BindView(tab1Model: TAB1Model) {
        imgProdTAB1.setImageResource(tab1Model.getProdImgTAB1())
        this.tab1Model = tab1Model
    }
  • Related