0

我的 recyclerview 片段: 这是我设置我的回收器视图的片段,我希望在点击继续按钮(btn_continue)时将列表的其余部分(实际上是下一页)添加到我的列表中,当我单击按钮但它会删除上一个列表并显示新列表,我使用 kotlin coruotine、viewmodel 和 recyclerview

 class AllUnpublishedAdsFragment : Fragment() {
          
            lateinit var unpublishedAdsAdapter: UnpublishedAdsAdapter
               var items = ArrayList<M_Ads>()
               lateinit var loadMoreItems: ArrayList<M_Ads>
               lateinit var scrollListener: RecyclerViewLoadMoreScroll
               lateinit var mLayoutManager: RecyclerView.LayoutManager
               val page = "1"
               var newpage = page.toInt()
           
               var navController: NavController? = null
               lateinit var btn_continue: Button
               private lateinit var viewModel: MainViewmodels
               lateinit var token: String
           
           
               override fun onCreateView(
                   inflater: LayoutInflater, container: ViewGroup?,
                   savedInstanceState: Bundle?
               ): View? {
                   // Inflate the layout for this fragment
                   return inflater.inflate(R.layout.fragment_all_unpublished_ads, container,
   false)
               }
           
               override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
                   super.onViewCreated(view, savedInstanceState)
                   btn_continue = view.findViewById<Button>(R.id.btn_continueAds)
                   token = arguments?.getString(TOKEN_KEY).toString()
                   Log.i("TOKEN", token)
                   setupViewModel(token, page)
           
                   continueAds()
           
           
           
           
                   unpublishedAdsAdapter.itemClickListener = { item, position ->
                       val id = item.id
                       val bundle_id = Bundle()
                       bundle_id.putString(ID_KEY, id.toString())
                       navController = Navigation.findNavController(view)
                       //view.findNavController().navigate(R.id.action_UnpublishedAds_to_Detail,
   bundle_id)
                       navController!!.navigate(
                           R.id.action_allUnpublishedAdsFragment_to_adsDetailFragment,
                           bundle_id
                       )
                   }
               }
           
               private fun setupViewModel(token: String, page: String) {
                   LoadingDialog.show(requireContext(), { ld ->
                       recy_unpublished_ads.layoutManager = LinearLayoutManager(activity)
                       val decoration = DividerItemDecoration(activity, DividerItemDecoration.VERTICAL)
                       recy_unpublished_ads.addItemDecoration(decoration)
                       viewModel = ViewModelProvider(this).get(MainViewmodels::class.java)
                       unpublishedAdsAdapter = UnpublishedAdsAdapter()
                       recy_unpublished_ads.adapter = unpublishedAdsAdapter
                       viewModel.adsListObserve().observe({ lifecycle }, { model ->
           
                           items.clear()
                           items.addAll(model.adsList!!)
                           unpublishedAdsAdapter.setUpdateData(items)
                           ld.dismiss()
                           btn_continue.visibility = View.VISIBLE
                       })
                       viewModel.getAdsList(token, page)
           
                   })
               }
           
                   fun continueAds() {
                   var isTouched=false
                   btn_continue.setOnClickListener {
                       isTouched=true
                       newpage = newpage + 1
                       Log.i("CONTINUE", newpage.toString())
                       setupViewModel(token, newpage.toString())
                       unpublishedAdsAdapter.notifyDataSetChanged()
                       isTouched=false
                   }
               }

RetrofitInstance 类

class RetrofitInstance {

    companion object{

        fun getRetrofitInstance (): Retrofit{
//            val interceptor = HttpLoggingInterceptor()
//            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
//            val client: OkHttpClient = OkHttpClient.Builder().addInterceptor(interceptor).build()
            val okHttpClient: OkHttpClient = OkHttpClient.Builder()
                .readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60, TimeUnit.SECONDS)
                .build()

            return  Retrofit.Builder()
                .baseUrl(BASEURL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build()
        }
    }
}

我的适配器:

class UnpublishedAdsAdapter : RecyclerView.Adapter<UnpublishedAdsAdapter.MyViewHolder>() {

    var items = ArrayList<M_Ads>()
    var itemClickListener: ((item: M_Ads, position: Int) -> Unit)? = null
    lateinit var mcontext: Context

    class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
    class LoadingViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

    fun setUpdateData(items: ArrayList<M_Ads>) {
        this.items = items
        notifyDataSetChanged()
    }



    class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val img_ads = view.findViewById<ImageView>(R.id.img_recy_ads)
        val txt_title = view.findViewById<TextView>(R.id.txt_recy_ads_title)
        val txt_accountType = view.findViewById<TextView>(R.id.txt_recy_ads_acctype)
        fun bind(data: M_Ads) {
            txt_title.setText(data.title)
            txt_accountType.setText(data.accountType)
            if (!data.image1.equals("")) {
                Picasso.with(img_ads.context).load(data.image1).into(img_ads)
            } else {
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {

        mcontext = parent.context
        return if (viewType == Constant.VIEW_TYPE_ITEM) {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.row_recy_unpublished_ads, parent, false)
            MyViewHolder(view)
        } else {
            val view =
                LayoutInflater.from(mcontext).inflate(R.layout.progress_loading, parent, false)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                view.progressbar.indeterminateDrawable.colorFilter =
                    BlendModeColorFilter(Color.WHITE, BlendMode.SRC_ATOP)
            } else {
                view.progressbar.indeterminateDrawable.setColorFilter(
                    Color.WHITE,
                    PorterDuff.Mode.MULTIPLY
                )
            }
            MyViewHolder(view)
        }

    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.bind(items.get(position))
        handleClick(holder)

    }

    fun handleClick(holder: UnpublishedAdsAdapter.MyViewHolder) {
        holder.itemView.setOnClickListener {
            val position = holder.adapterPosition
            itemClickListener?.invoke(items.get(position), position)
        }
    }

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

我的视图模型:

class MainViewmodels:ViewModel() {
    lateinit var getAds:MutableLiveData<Main_ModelAds>
    init {
        getAds= MutableLiveData<Main_ModelAds>()
    }
    fun adsListObserve():MutableLiveData<Main_ModelAds>{
        return getAds
    }
    fun getAdsList(token:String,page:String){
        viewModelScope.launch(Dispatchers.IO) {
            try {
                Log.i("ERRORRES",token + "")
                val retrofitInstance=RetrofitInstance.getRetrofitInstance().create(RetrofitService::class.java)
                val response=retrofitInstance.unPublishedAdsList(token,page)
                getAds.postValue(response)
            }catch (ex:Exception){
                Log.i("ERRORRES", ex.message.toString() + "")
            }
        }

    }
4

1 回答 1

0

您在这里想要的是更新用户单击按钮时显示的列表。在这种情况下,您应该使用 ListAdapter。

实现可以参考这篇文章: https ://developer.android.com/reference/androidx/recyclerview/widget/ListAdapter

于 2022-02-12T15:15:10.417 回答