RecyclerView不更新具有位置的项目

时间:2017-01-17 04:11:07

标签: android pagination android-recyclerview

我使用JSON从服务器将项目加载到recyclerview中,维护Adapter类以通过hashmap方法设置数据。我正在为recyclerView使用分页。每个页面包含10个项目,并且在达到10个项目后页面递增。

问题是,加载后,当用户点击项目时,它不会刷新。

HomeClass是一个启动器活动:

public class HomeClass  extends AppCompatActivity {

   protected void onCreate(Bundle savedInstanceState) {
      sendID(url);
    }

      public void sendID(final String url){
        if (progress == null) {
            progress = new ProgressDialog(this);
            progress.show();
        }
        Constant.Home_Posts.clear();
        new Thread(new Runnable(){
            @Override
            public void run() {
           ///pagecount is 1 in HomeClass by default
               JSONObject responseObj = new JSONObject(arg0);

          HashMap<String, String> map = new HashMap<String, String>();
                 map.put(key,value);
                Constant.Home_Posts.add(map);
                }
             }
                if (progress!=null) {
                  if (progress.isShowing()) {
                     progress.dismiss();
                     progress = null;
               Intent intent = new Intent(HomeClass.this, Home.class);
                     startActivity(intent);
                     finish();
                  }
        }

第二类Home,只包含onBindViewHolder

       public class Home extends AppCompatActivity {
       protected void onCreate(Bundle savedInstanceState) {
       }

      private void getPostCount(final String URl) {
        if (progress == null) {
            progress = new ProgressDialog(this);
            progress.show();
        }
         new Thread(new Runnable() {
            @Override
            public void run() {

                viewposition = viewposition + 10;
                getPostUrl = "url+userid="+ userID+ "&page="+ page_count;

           //pagecount is 2 in 'Home' by default and then icrements
           JSONObject responseObj = new JSONObject(arg0);

               HashMap<String, String> map = new HashMap<String, String>();
                 map.put(key,value);
                Constant.Home_Posts.add(map);
                     '
                     '
                }
             }
            }
            page_count++;

适配器类:

class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

  public void onBindViewHolder(RecyclerView.ViewHolder holder,final int i) {
            if (Constant.Home_Posts.size() - 1 == i) {
                Constant.Home_Posts.clear();
                getPostCount("url+ userID + "&page=" + page_count);
            }

         //set value using hashmap method from server
        viewHolder.imgComment.setText(value) //with integer values


       //OmCLick to update datas from user    
       viewHolder.imgComment.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {

                //get layout view by LayoutIflater and load data from server

                // create alert dialog
                final AlertDialog alertDialog = alertDialogBuilder.create();
               //user can comment anyhting,if success comment value in count 
               //should increment or comments should not change                 

                 sendComment.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View v) {

                            if (commentStatus == 0) {
                            } else {
                              alertDialog.cancel();


           String putLikesValue=(Integer.toString(Integer.parseInt(
                Constant.Home_Posts.get(i).get("comments_count"))+1));

           viewHolder.txtComment.setText(putLikesValue+"Comments");

                 notifyDataSetChanged();
                     notifyItemChanged(i);
                 });
               }

结果就像, 旧项目列出了更新的项目(新插入的项目)。

如何正确插入位置项目?

2 个答案:

答案 0 :(得分:1)

Hello使用它来加载所有数据。

 public FriendsAdapterSwipe(List<FriendListModel> alFriendListModel,RecyclerView recyclerView,Context context)
 {
    this.alFriendListModel = alFriendListModel;
    this.context=context;

    if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {

        final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                totalItemCount = linearLayoutManager.getItemCount();
                lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                if (!loading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
                    if (onLoadMoreListener != null) {
                        onLoadMoreListener.onLoadMore();
                    }
                    loading = true;
                }
            }
        });
    }
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    RecyclerView.ViewHolder vh;
    if (viewType == VIEW_ITEM)
    {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.raw_friends_swipe, parent, false);
        vh = new CustomViewHolder(itemView);
    } else
    {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.progressbar_item, parent, false);
        vh = new ProgressViewHolder(v);
    }
    return vh;
}

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {

    if (holder instanceof CustomViewHolder)
    {
        Typeface AvenirNextRegular = Fonts.AvenirNextRegular(context);
        holder.setIsRecyclable(false);
        FriendListModel model = alFriendListModel.get(position);
        ((CustomViewHolder) holder).txtUname.setText(model.getFullName());
        ((CustomViewHolder) holder).txtUname.setTypeface(AvenirNextRegular);

        if (alFriendListModel.get(position).getIsImageAvaible().equalsIgnoreCase("1"))
        {
            Glide.clear(((CustomViewHolder) holder).imgProfile);
            Glide.with(context).load(WebField.PROFILE_URL + alFriendListModel.get(position).getFriendId()
                    + "_small.png").asBitmap()
                    .placeholder(R.drawable.user_pic).skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.ALL).
                    fitCenter().into(new BitmapImageViewTarget(((CustomViewHolder) holder).imgProfile)
            {
                @Override
                protected void setResource(Bitmap resource)
                {
                    Drawable d = new BitmapDrawable(context.getResources(), resource);
                    ((CustomViewHolder) holder).imgProfile.setImageDrawable(d);
                }
            });
        }
    }
    else
    {
        ((CustomViewHolder) holder).imgProfile.setImageResource(R.drawable.user_pic);
    }
}

@Override
public int getItemCount() {
    return alFriendListModel.size();
}

@Override
public int getItemViewType(int position) {
    return alFriendListModel.get(position) != null ? VIEW_ITEM : VIEW_PROG;
}

public interface OnLoadMoreListener {
    void onLoadMore();
}

public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
    this.onLoadMoreListener = onLoadMoreListener;
}

public static class CustomViewHolder extends RecyclerView.ViewHolder
{
    TextView txtUname;
    CircularImageView imgProfile;;

    public CustomViewHolder(View itemView) {
        super(itemView);
        txtUname = (TextView) itemView.findViewById(R.id.txtUname);
        imgProfile = (CircularImageView) itemView.findViewById(R.id.imgProfile);
    }
}

public static class ProgressViewHolder extends RecyclerView.ViewHolder {
    public ProgressBar progressBar;

    public ProgressViewHolder(View v) {
        super(v);
        progressBar = (ProgressBar) v.findViewById(R.id.progressBar);
    }
}
public void setLoaded() {
    loading = false;
}

答案 1 :(得分:0)

您可以使用加载程序根据页面设置数据。

$(document).ready(function() {
  $(document).on('keydown.autocomplete', '#mytable tbody>tr:last input', function() {
      $(this).autocomplete({
            source: availableAttributes
        });
  });
    $("#add").click(function() {
        var newIndex = globalNewIndex+1;
        var changeIds = function(i, val) {
            return val.replace(globalNewIndex,newIndex);
        }
        var $newRow = $('<tr class="person"><td><input type="text" class="form-control emptythis ui-autocomplete-input" autocomplete="off"></td><td><input type="number" name="fixed_price[1]" id="fixed_price_1" class="form-control emptythis" autocomplete="off"></td></tr>');
        $newRow.insertAfter('#mytable tbody>tr:last');
        $('#mytable tbody>tr:last input').attr('name', changeIds ).attr('id', changeIds);
           globalNewIndex++;
        $('#mytable tbody>tr:last .emptythis').val('');
        $("#mytable tbody>tr:last").each(function() {this.reset();});

      return false;
    });
});