如何从嵌套回收器视图子适配器返回片段

问题描述 投票:0回答:1

在我的 kotlin 项目中,从主要活动中,从底部菜单添加了一个片段(peoplenearby 片段)。在该片段中,通过嵌套回收器视图配置文件图像和查看的名称。如果单击个人资料图像,它会打开另一个片段(ProfileviewPeople),然后如果在 Android 手机中按下后退按钮,它会转到主活动。我需要从 profileviewpeople 返回到 peoplenearby 片段页面。我添加了 ChildAdapter 代码,从 ChildAdapter 我单击了 profileviewpeople 片段实例。我已经添加了人员附近的片段传递数组列表代码、父适配器和子适配器代码

private fun loadAndDisplayProfile(uid: Int, cntxt: Context) {
    val bundle = Bundle()
    bundle.putInt("userId", uid)
    val fragment = ProfileViewPeople.newInstance(uid).apply {
        arguments = bundle
    }
    val appCompatActivity = cntx as AppCompatActivity
    appCompatActivity.supportFragmentManager.beginTransaction()
        .setCustomAnimations( R.anim.slide_in_right,
            R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right )
        .add(R.id.peopleNearBy, fragment).addToBackStack("selectx")
        .commit()

    Log.d("ChildAdapter", " backStackEntryCount "+appCompatActivity.supportFragmentManager.backStackEntryCount)
}

完整代码:

class ChildAdapter(private val 

myChildList:MutableList<Peoples>):RecyclerView.Adapter<ChildAdapter.ChildHolder>() {   

 class ChildHolder(itemView: View):RecyclerView.ViewHolder(itemView)
{
        val title1:TextView
        val title2:TextView
        val title3:TextView
        val title4:TextView
        val title5:TextView
        val title6:TextView
        val title7:TextView
        val title8:TextView
        val title9:TextView
        val title10:TextView
        val title11:TextView
        val title12:TextView
        val img1:ImageView
        val img2:ImageView
        val img3:ImageView
        val img4:ImageView
        val img5:ImageView
        val img6:ImageView
        val img7:ImageView
        val img8:ImageView
        val img9:ImageView
        val img10:ImageView
        val img11:ImageView
        val img12:ImageView
        init {
            title1 = itemView.findViewById(R.id.child_title1)
            title2 = itemView.findViewById(R.id.child_title2)
            title3 = itemView.findViewById(R.id.child_title3)
            title4 = itemView.findViewById(R.id.child_title4)
            title5 = itemView.findViewById(R.id.child_title5)
            title6 = itemView.findViewById(R.id.child_title6)
            title7 = itemView.findViewById(R.id.child_title7)
            title8 = itemView.findViewById(R.id.child_title8)
            title9 = itemView.findViewById(R.id.child_title9)
            title10 = itemView.findViewById(R.id.child_title10)
            title11 = itemView.findViewById(R.id.child_title11)
            title12 = itemView.findViewById(R.id.child_title12)
            img1 = itemView.findViewById(R.id.child_img1)
            img2 = itemView.findViewById(R.id.child_img2)
            img3 = itemView.findViewById(R.id.child_img3)
            img4 = itemView.findViewById(R.id.child_img4)
            img5 = itemView.findViewById(R.id.child_img5)
            img6 = itemView.findViewById(R.id.child_img6)
            img7 = itemView.findViewById(R.id.child_img7)
            img8 = itemView.findViewById(R.id.child_img8)
            img9 = itemView.findViewById(R.id.child_img9)
            img10 = itemView.findViewById(R.id.child_img10)
            img11 = itemView.findViewById(R.id.child_img11)
            img12 = itemView.findViewById(R.id.child_img12)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChildHolder {
        val mView = LayoutInflater.from(parent.context).inflate(R.layout.child_item, parent, false)
        return ChildHolder(mView)
    }

    override fun onBindViewHolder(holder: ChildHolder, position: Int) {
        val title1 = myChildList[position].title1
        holder.title1.text = if (title1.length>10){
            title1.substring(0,10)+"..."
        }else{
            title1
        }
        val title2 = myChildList[position].title2
        holder.title2.text = if (title2.length>10){
            title2.substring(1,10)+"..."
        }else{
            title2
        }
        val title3 = myChildList[position].title3
        holder.title3.text= if (title3.length>10){
            title3.substring(0,10)+"..."
        }else{
            title3
        }
        val title4 = myChildList[position].title4
        holder.title4.text = if (title4.length>10){
            title4.substring(0,10)+"..."
        }else {
            title4
        }
        val title5 = myChildList[position].title5
        holder.title5.text = if (title5.length>10){
            title5.substring(0,10)+"..."
        }else{
            title5
        }

        val title6 = myChildList[position].title6
        holder.title6.text = if (title6.length>10){
            title6.substring(0,10)+"..."
        }else{
            title6
        }
        val title7=myChildList[position].title7
        holder.title7.text = if (title7.length>10){
            title7.substring(0,10)+"..."
        }else{
            title7
        }
        val title8=myChildList[position].title8
        holder.title8.text = if (title8.length>10){
            title8.substring(0,10)+"..."
        }else{
            title8
        }
        val title9=myChildList[position].title9
        holder.title9.text = if (title9.length>10){
            title9.substring(0,10)+"..."
        }else{
            title9
        }
        val title10=myChildList[position].title10
        holder.title10.text = if (title10.length>10){
            title10.substring(0,10)+"..."
        }else{
            title10
        }
        val title11=myChildList[position].title11
        holder.title11.text = if (title11.length>10){
            title11.substring(0,10)+"..."
        }else{
            title11
        }
        val title12 =myChildList[position].title12
        holder.title12.text = if (title12.length>10){
            title12.substring(0,10)+"..."
        }else{
            title12
        }

        loadAndDisplayImage(myChildList[position].img1, holder.img1)
        loadAndDisplayImage(myChildList[position].img2, holder.img2)
        loadAndDisplayImage(myChildList[position].img3, holder.img3)
        loadAndDisplayImage(myChildList[position].img4, holder.img4)
        loadAndDisplayImage(myChildList[position].img5, holder.img5)
        loadAndDisplayImage(myChildList[position].img6, holder.img6)
        loadAndDisplayImage(myChildList[position].img7, holder.img7)
        loadAndDisplayImage(myChildList[position].img8, holder.img8)
        loadAndDisplayImage(myChildList[position].img9, holder.img9)
        loadAndDisplayImage(myChildList[position].img10, holder.img10)
        loadAndDisplayImage(myChildList[position].img11, holder.img11)
        loadAndDisplayImage(myChildList[position].img12, holder.img12)

        holder.img1.setOnClickListener {
            loadAndDisplayProfile(myChildList[position].userid1, holder.img1.context)
        }

        holder.img2.setOnClickListener {
            loadAndDisplayProfile(myChildList[position].userid2, holder.img2.context)
        }

        holder.img3.setOnClickListener {
            loadAndDisplayProfile(myChildList[position].userid3, holder.img3.context)
        }

        holder.img4.setOnClickListener {
            loadAndDisplayProfile(myChildList[position].userid4, holder.img4.context)
        }

        holder.img5.setOnClickListener {
            loadAndDisplayProfile(myChildList[position].userid5, holder.img5.context)
        }

        holder.img6.setOnClickListener {
            loadAndDisplayProfile(myChildList[position].userid6, holder.img6.context)
        }

        holder.img7.setOnClickListener {
            loadAndDisplayProfile(myChildList[position].userid7, holder.img7.context)
        }

        holder.img8.setOnClickListener {
            loadAndDisplayProfile(myChildList[position].userid8, holder.img8.context)
        }

        holder.img9.setOnClickListener {
            loadAndDisplayProfile(myChildList[position].userid9, holder.img9.context)
        }

        holder.img10.setOnClickListener {
            loadAndDisplayProfile(myChildList[position].userid10, holder.img10.context)
        }

        holder.img11.setOnClickListener {
            loadAndDisplayProfile(myChildList[position].userid11, holder.img11.context)
        }

        holder.img12.setOnClickListener {
            loadAndDisplayProfile(myChildList[position].userid12, holder.img12.context)
        }
    }

    override fun getItemCount(): Int {
        return myChildList.size
    }

    private fun loadAndDisplayImage(imageUrl: String, imageView: ImageView) {
        if (imageUrl.isNotEmpty()) {
            try {
                Glide.with(imageView.context)
                    .asBitmap()
                    .load(imageUrl)
                    .placeholder(R.drawable.male_avatar)
                    .circleCrop()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(imageView)
            } catch (e: Exception) {
                e.printStackTrace() // Handle any exceptions that may occur during the loading process
            }
        } else {           
            Glide.get(imageView.context).clearDiskCache()
        }
    }

    private fun loadAndDisplayProfile(uid: Int, cntxt: Context) {
        val bundle = Bundle()
        bundle.putInt("userId", uid)
        val fragment = ProfileViewPeople.newInstance(uid).apply {
            arguments = bundle
        }
        val appCompatActivity = cntxt as AppCompatActivity
        appCompatActivity.supportFragmentManager.beginTransaction()
            .setCustomAnimations( R.anim.slide_in_right,
                R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right )
            .replace(R.id.peopleNearBy, fragment).addToBackStack("selectx")
            .commit()
    }
}

家长适配器:

@ExperimentalCoroutinesApi
class ParentAdapter(private val context: Context, var parentList:ArrayList<PeopleNearByModelClass>):RecyclerView.Adapter<ParentAdapter.ParentHolder>() {
    private lateinit var childAdapter:ChildAdapter

    class ParentHolder(itemView:View):RecyclerView.ViewHolder(itemView){
        //val title:TextView
        val mRecyclerView:RecyclerView
        init {
            //title = itemView.findViewById(R.id.parent_title)
            mRecyclerView = itemView.findViewById(R.id.child_recyclerview)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ParentHolder {
        val mView = LayoutInflater.from(parent.context).inflate(R.layout.parent_item, parent, false)
        return ParentHolder(mView)
    }

    override fun onBindViewHolder(holder: ParentHolder, position: Int) {     

        childAdapter = ChildAdapter(parentList[position].movieList)
        holder.mRecyclerView.layoutManager =
            LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
        holder.mRecyclerView.adapter = childAdapter


        if ( position == 0) {
            val template =
                holder.itemView.findViewById<TemplateView>(R.id.my_template)
            template.visibility = View.GONE
        }
        else if (size == position) {
            val template =
                holder.itemView.findViewById<TemplateView>(R.id.my_template)
            template.visibility = View.GONE
        }
        else  {
            MobileAds.initialize(context) {
                val adLoader: AdLoader =
                    AdLoader.Builder(context, "ca-app-pub-3940256099942544/2247696110")
                        .forNativeAd { nativeAd -> 
                            //                        if (isDestroyed) {
                            //                          nativeAd.destroy()
                            //                            return
                            //                        }
                            val styles = NativeTemplateStyle.Builder().build()
                            val template =
                                holder.itemView.findViewById<TemplateView>(R.id.my_template)
                            template.setStyles(styles)
                            template.visibility = View.VISIBLE
                            template.setNativeAd(nativeAd)
                        }
                        .withAdListener(object : AdListener() {
                            override fun onAdFailedToLoad(adError: LoadAdError) {
                                
                            }
                        })
                        .withNativeAdOptions(
                            NativeAdOptions.Builder()
                                .build()
                        )
                        .build()
                adLoader.loadAd(AdRequest.Builder().build())
            }
        }
    }

    override fun getItemCount(): Int {
        return parentList.size
    }   
}

嵌套回收器视图附近的人员片段代码:

private suspend fun loopArray(peoplnearbylists:MutableList<List<PeopleNearByModelClass>>, lastarraysize: JSONArray) {
    val lastArrayList = lastarraysize

    val totalSize = peoplnearbylists.size

    val rowLists = peoplnearbylists
    //  val totalsize = peoplnearbylists.size

    for (index in 0 until totalSize) {
        val rowList = rowLists[index]
        val maxUsers = minOf(rowList.size, 12) // Update the maximum number of users per row
        val uniqueUserSet = HashSet<String>() // Track unique user names

        val peopleList = mutableListOf<Peoples>()
        for (i in 0 until maxUsers step 12) {
            val person1 = rowList[i]
            val person2 = rowList[i + 1]
            val person3 = rowList[i + 2]
            val person4 = rowList[i + 3]
            val person5 = rowList[i + 4]
            val person6 = rowList[i + 5]
            val person7 = rowList[i + 6]
            val person8 = rowList[i + 7]
            val person9 = rowList[i + 8]
            val person10 = rowList[i + 9]
            val person11 = rowList[i + 10]
            val person12 = rowList[i + 11]
            peopleList.add(
                Peoples(
                    title1 = person1.userName,
                    img1 = person1.userImage,
                    userid1 = person1.userID,
                    title2 = person2.userName,
                    img2 = person2.userImage,
                    userid2 = person2.userID,
                    title3 = person3.userName,
                    img3 = person3.userImage,
                    userid3 = person3.userID,
                    title4 = person4.userName,
                    img4 = person4.userImage,
                    userid4 = person4.userID,
                    title5 = person5.userName,
                    img5 = person5.userImage,
                    userid5 = person5.userID,
                    title6 = person6.userName,
                    img6 = person6.userImage,
                    userid6 = person6.userID,
                    title7 = person7.userName,
                    img7 = person7.userImage,
                    userid7 = person7.userID,
                    title8 = person8.userName,
                    img8 = person8.userImage,
                    userid8 = person8.userID,
                    title9 = person9.userName,
                    img9 = person9.userImage,
                    userid9 = person9.userID,
                    title10 = person10.userName,
                    img10 = person10.userImage,
                    userid10 = person10.userID,
                    title11 = person11.userName,
                    img11 = person11.userImage,
                    userid11 = person11.userID,
                    title12 = person12.userName,
                    img12 = person12.userImage,
                    userid12 = person12.userID
                )
            )
        }

        mParentList.add(Parent("", peopleList))

    }

    mAdapter = ParentAdapter(requireContext(), mParentList, totalSize)

    withContext(Dispatchers.Main) {
        mRecyclerView.layoutManager = LinearLayoutManager(requireContext())
        mRecyclerView.adapter = mAdapter
    }
}

A

android kotlin android-fragments android-recyclerview view
1个回答
1
投票

请考虑使用视图绑定。您的代码很难理解:https://developer.android.com/topic/libraries/view-binding。包括在您的视图持有者中以及您看到大量代码行的任何地方,请考虑创建集合并通过 for 循环和调用函数来遍历它们。鸡蛋:

onBindViewHolder(...){
 ....
  setTitileText(listOf(holder.title1,holder.title2 ...),listOf(title1,titel2...))
 ....
}
....
fun setTitileText(ar : List<View>,titles :List<String>){
     for (index in 0 until ar.size){
         if(titles.size <= index) continue   
         index = if (title1.length>10) title1.substring(0,10)+"..."else title1
     }
}

至于如何拦截 onBackPressed 事件,您需要在父 Activity 中添加使用

onCreate()
 的回调
onBackPresedDispatcher

© www.soinside.com 2019 - 2024. All rights reserved.