我想做什么:当用户在edittext中输入内容时,API调用并在recyclerview中显示响应。
usersData= ArrayList()
resultRecyclerView.setHasFixedSize(true)
resultRecyclerView.layoutManager=LinearLayoutManager(
this@MainActivity,LinearLayoutManager.VERTICAL,false)
itemsAdapter=adapter(this@MainActivity,usersData)
resultRecyclerView.adapter=itemsAdapter
在OnResume()
中searchText.addTextChangedListener(object : TextWatcher {
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
//....
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
//.......
}
override fun afterTextChanged(s: Editable) {
Log.v("Text is ",s.toString())
val url="https://api.github.com/search/users?q="+s.toString().trim()+"+sort:followers"
fetchData(url)
}
})
获取数据的方法
private fun fetchData(url: String) {
val tag_string_req = "string_req"
val strReq = StringRequest(Request.Method.GET,
url, Response.Listener<String> {
response ->
Log.d(TAG, response.toString())
val builder = GsonBuilder()
val gson = builder.create()
//val allItems=gson.fromJson(response,AllUsers::class.java)
val data=gson.fromJson(response,AllUsers::class.java)
usersData=data.items
Log.v("No of users",usersData?.size.toString())
resultRecyclerView.removeAllViews()
itemsAdapter?.notifyDataSetChanged()
}, Response.ErrorListener { error ->
VolleyLog.d(TAG, "Error: " + error.message)
})
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req)
}
但是更新的数据没有传入适配器(它仍然没有数据)。我从API
得到了预期的回复。 notifyDataSetChanged()
未更新列表。
答案 0 :(得分:0)
我认为notifyDataSetChanged也会自动更新数据,但没有。
我需要致电
itemsAdapter?.updateData(usersData)
并在适配器中:
fun updateData(users: ArrayList<Items>?){
this.users=users
}
答案 1 :(得分:0)
在适配器中添加此方法
fun addData(exList: MutableList<Object>) {
items.clear()
items.addAll(exList)
notifyDataSetChanged()
}
并添加您的活动/片段中的数据
projectsAdapter.addData(list as MutableList<Object>)