初始化:
postLine.setAdapter(postsAdapter);
postLine.setLayoutManager(new GridLayoutManager(getActivity(),2));
,準備後添加他們recyclerView功能
private void preparePosts(JSONArray posts){
listOfLine1.clear(); //SparseArray
listOfLine2.clear(); //SparseArray
postLine.removeAllViews(); //RecyclerView
postList.clear(); //ListArray postList
int postline2h = 0;
int postline1h = 0;
try{
Post ps;
for(int i = 0; i
ps = new Post(posts.getJSONObject(i));
if(postline1h>postline2h){
listOfLine2.put(listOfLine2.size(),ps);
postline2h += ps.getHeight();
}else{
postline1h += ps.getHeight();
listOfLine1.put(listOfLine1.size(),ps);
}
}
int i =0;
boolean firstnull,secondnull;
while (i!=listOfLine2.size()-1 || i!=listOfLine1.size()-1){
if(listOfLine1.get(i)!=null){
firstnull = false;
postList.add(listOfLine1.get(i));
listOfLine1.remove(i);
}else firstnull = true;
if(listOfLine2.get(i)!=null){
secondnull = false;
postList.add(listOfLine2.get(i));
listOfLine2.remove(i);
}else secondnull = true;
if(secondnull && firstnull) break;
i++;
}
postsAdapter.notifyDataSetChanged();
}catch (Exception e){
log(e);
}
}}
適配器:
public class PostsAdapter extends RecyclerView.Adapter {
private ArrayList posts;
public PostsAdapter(ArrayList postslist){
posts = postslist;
}
@Override
public int getItemCount() {
return posts.size();
}
@Override
public PostsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new PostsHolder(new LinearLayout(parent.getContext()));
}
@Override
public void onBindViewHolder(PostsHolder holder, int position) {
holder.setPost(posts.get(position));
}
@Override
public void onViewRecycled(PostsHolder holder) {
super.onViewRecycled(holder);
holder.getPost().die();
}
}
onBindViewHolder post.setPost是要添加的意見到佈局