我知道已经问过这个问题,但是检查了答案后,我仍然找不到解决方案。这是我的适配器:
public static class StarredReposViewHolder extends RecyclerView.ViewHolder {
LinearLayout starredReposLayout;
TextView starredRepoName;
public StarredReposViewHolder(View v) {
super(v);
starredReposLayout = (LinearLayout) v.findViewById(R.id.repo_starred_item_layout);
starredRepoName = (TextView) v.findViewById(R.id.starredepoName);
}
}
public StarredReposAdapter(List<GitHubstarredRepos> repos, int rowLayout, Context context) {
this.starredRepos = repos;
this.rowLayout = rowLayout;
this.context = context;
}
@Override
public StarredReposAdapter.StarredReposViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new StarredReposViewHolder(view);
}
@Override
public void onBindViewHolder(StarredReposViewHolder holder, int position) {
holder.starredRepoName.setText(starredRepos.get(position).getStarredName());
}
@Override
public int getItemCount() {
return starredRepos.size();
}
这是我加载它的方法:
public void loadStarredRepos (View view){
final RecyclerView recyclerViewSt = (RecyclerView) findViewById(R.id.starred_repos_recycler_view);
recyclerViewSt.setLayoutManager(new LinearLayoutManager(this));
GitHubStarredRepoAPI apiService =
ApiClient.getClient().create(GitHubStarredRepoAPI.class);
Call<List<GitHubstarredRepos>> call = apiService.getStarredRepoName(newString);
call.enqueue(new Callback<List<GitHubstarredRepos>>() {
@Override
public void onResponse(Call<List<GitHubstarredRepos>> call, Response<List<GitHubstarredRepos>>
response) {
recyclerViewSt.setAdapter(new StarredReposAdapter(response.body(), R.layout.list_item_starred_repo,
getApplicationContext()));
}
@Override
public void onFailure(Call<List<GitHubstarredRepos>> call, Throwable t) {
// Log error here since request failed
Log.e("Repos", t.toString());
}
});
}
onResponse的正文输入正确。问题不能在于它是在onCreate中定义的,因为我在同一屏幕上具有从另一个方法加载的另一个“回收视图”。谢谢!
PS:response.body()的响应
最佳答案
好吧,从实践出发,您应该在#onCreate()的mainThread中拥有RecyclerView#setAdapter() public void onCreate() { recyclerViewSt.setAdapter(myAdapter); }
您需要在onResponse()中更新的是用于提供适配器的dataSet。
您可以提取response.body(),该对象将对象数组(列表存储库)返回到活动中的全局变量中。喜欢:List<GitHubstarredRepos> myDatasource = new ArrayList<>();
然后使用它:myAdapter = new StarredReposAdapter(myDatasource, R.layout.list_item_starred_repo, getApplicationContext()));
接下来,在网络调用的回调中:onResponse(response) { myDatasource.clear(); myDatasource.addAll(response.body()); myRecyclerview.notifyDatasetChanged();}
瞧,我的psedocode代码,不确定语法;)