1

我想在两个以上的函数中访问后期初始化变量我该如何使用它?实际上,当请求接受或拒绝时,我想从 recyclerview 中删除该项目

1.这是我的片段类

lateinit var adapterPendingRequest: FriendsPendingRequestAdapter
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    floatingActionButton = view.findViewById(R.id.addFriendFloatingButton)

    recyclerPendingRequest = view.pendingRequestsRecyclerId
    recyclerPendingRequest.layoutManager = LinearLayoutManager(requireContext())

    recyclerViewFriendList = view.friendListRecyclerView
    recyclerViewFriendList.layoutManager = LinearLayoutManager(requireContext())
    adapterPendingRequest = FriendsPendingRequestAdapter(activity!!)


    floatingActionButton.setOnClickListener {
        findNavController().navigate(R.id.action_friendListFragmentId_to_searchFriendFragment)
    }

    actionMoreButton = view.moreMenuOptionId
    actionMoreButton.setOnClickListener {
        showPopup()
    }


    //Get FriendRequest Function
    getFriendRequest()

    //FriendList
    addedFriendsList()

    Log.e("size", modelPendingRequest.size.toString())

}  

2.这个适配器在getFriendRequest函数中工作正常 这是我从recyclerview中的服务器获取列表并接受或拒绝请求但项目没有在按钮单击时删除的函数

private fun getFriendRequest() {
    val getHttpRequest = HttpRequest()

    Log.e("ResponseText","Inside fun")

    getHttpRequest.setOnResponseListener { getRequestResponse ->
        Log.e("ResponseText", getRequestResponse.text)
        Log.e("get ResponseCode", getRequestResponse.code.toString())
        if (getRequestResponse.code == HttpResponse.HTTP_OK) {
            Log.e("get in ResponseCode", getRequestResponse.code.toString())

            val jsonArray = getRequestResponse.toJSONArray()
            modelPendingRequest.clear()
            for (i in 0 until jsonArray!!.length()) {
                val jsonObject = jsonArray.getJSONObject(i)
                val getRequestUserName = jsonObject.getString("username")
                val getRequestImage = jsonObject.getString("image")
                val getRequestFirstName = jsonObject.getString("first_name")
                val getRequestLastName = jsonObject.getString("last_name")

                modelPendingRequest.add(SearchUserModel(getRequestUserName,getRequestImage,getRequestFirstName,getRequestLastName))
                //adapter to set all data in recyclerview
                adapterPendingRequest.setData(modelPendingRequest)
                
                recyclerPendingRequest.adapter = adapterPendingRequest
                Log.e("sizes", modelPendingRequest.size.toString())

                appGlobals.saveString("requestUser", getRequestUserName)
            }

        } else if (getRequestResponse.code != HttpResponse.HTTP_OK) {
            Toast.makeText(requireContext(), getRequestResponse.text, Toast.LENGTH_SHORT).show()
        }
    }

    getHttpRequest.setOnErrorListener {
        Log.e("Get Request Error", it.toString())
    }

    val token = appGlobals.getValueString("userToken")
    Log.e("requestToken", token.toString())
    val headers = HttpHeaders("Authorization", "Token $token")
    getHttpRequest.get(AppGlobals.GET_FRIEND_REQUEST_API, headers)
    Log.e("ResponseText","end of fun")

}}

3. 但不在这里

fun acceptRequest(position: Int) {

    val acceptHttRequest = HttpRequest()
    val jsonObject = JSONObject()
    acceptHttRequest.setOnResponseListener { acceptResponse ->

        Log.e("accept ResponseText", acceptResponse.text)
        Log.e("accept ResponseCode", acceptResponse.code.toString())

        if (acceptResponse.code == HttpResponse.HTTP_OK) {
            Log.e("accept ResponseCode", acceptResponse.code.toString())

            Log.e("sizes", modelPendingRequest.size.toString())

            adapterPendingRequest.removePosition(position)

        }
    }

    acceptHttRequest.setOnErrorListener {
        Log.e("Accept Request Error", it.toString())
    }

    val userName = appGlobals.getValueString("requestUser")
    Log.e("Accept Request", "$userName")

    try {
        jsonObject.put("username", userName)
    } catch (e: JSONException) {
        Log.e("Accept Request Error", "Error here")
    }
    val token = appGlobals.getValueString("userToken")
    val headers = HttpHeaders("Authorization", "Token $token")

    acceptHttRequest.post(AppGlobals.ACCEPT_FRIEND_REQUEST_API, jsonObject, headers)
}

这是适配器类

Class FriendsPendingRequestAdapter(activity: Activity): RecyclerView.Adapter<FriendsPendingRequestAdapter.RequestViewHolder>() {
    
        private var data = ArrayList<SearchUserModel>()
        private val requestActivity = activity
        private val friendListFragment = FriendListFragment()
        var removedPosition : Int ? = null
    
        class RequestViewHolder(requestView: View): RecyclerView.ViewHolder(requestView) {
    
        }
    
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RequestViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.friend_pending_request_list, parent, false)
            return RequestViewHolder(view)
        }
    
        override fun onBindViewHolder(holder: RequestViewHolder, position: Int) {
            val pendingRequest = data[position]
    
            holder.itemView.friendRequestNameId.text = "${pendingRequest.firstName} ${pendingRequest.lastName}"
            Log.e("Request Name", pendingRequest.firstName)
    
            Glide.with(requestActivity)
                .load("${AppGlobals.SERVER}${pendingRequest.image}")
                .into(holder.itemView.friendRequestImageId)
    
            holder.itemView.confirmRequestButtonId.setOnClickListener {
                requestActivity.let { friendListFragment.acceptRequest(position)
    //            data.removeAt(position)
                removedPosition = position
                notifyDataSetChanged()}
    
            }
    
            holder.itemView.cancelRequestButtonId.setOnClickListener {
                requestActivity.let {friendListFragment.declineRequest(position)
    //                data.removeAt(position)
                    removedPosition = position
                    notifyDataSetChanged()}
    
            }
        }
    
        override fun getItemCount(): Int {
            return data.size
        }
    
        fun setData(tasks: ArrayList<SearchUserModel>) {
            this.data = tasks
            notifyDataSetChanged()
        }
    
        fun removePosition(position: Int): Int? {
            data.removeAt(position)
            notifyDataSetChanged()
            return removedPosition
        }
4

2 回答 2

0

从适配器中手动实例化片段并像那样访问它似乎不合适。Android 组件的生命周期需要由 Android 来管理,所以如果像这样自己实例化,是无法onViewCreated在这个 Fragment 上调用的,所以不会在里面初始化 lateinit 属性。

注意还有一个更大的问题:fragment实例化了adapter,adapter实例化了一个fragment。适配器不可能使用与调用其构造函数的片段相同的片段。

一种解决方法是this在调用时将片段 () 传递给适配器的构造函数onViewCreated。但是我已经有一段时间没有做过 Android 开发了,所以我不确定适配器是否可以访问包含的片段。

其他重要说明:

  • 通常最好使用 read-onlyval而不是 mutable var,尤其是对于公共属性(它使代码更容易推理)

  • lateinit var当您比编译器更清楚何时初始化以及何时可以安全地访问它时,使用不可为空属性是一个技巧 - 但您显然为了“方便”而放弃了空安全性。使用公共 lateinit var是危险的,因为它使查看事件的确切顺序变得更加困难(当它被初始化时 VS 被访问时)。一般来说,一旦它公开,你就不能真正依赖于编译器以外的知识——你很可能会犯错误。因此,保持lateinit var可见性/范围尽可能小,以便轻松清楚地看到所有访问和初始化

于 2022-01-14T11:04:54.267 回答
0

函数 twoFun 中的适配器变量只是adapter代替adapterPendingRequest. 是这样吗?

于 2022-01-13T13:44:00.223 回答