Recycleview更新其布局

时间:2018-02-09 07:45:43

标签: android android-recyclerview recycler-adapter recyclerview-layout

我的问题在很多线程中都被问过,例如 How do I make RecyclerView update its layout?。 但不幸的是,他们都没有解决我的问题。 我在我的android项目中使用recycleview。对于每个项目我隐藏了复选框,我试图让它在长按时对所有项目可见。我试图调用:adapter.notifyItemChanged()在这种情况下,但没有。有时它更新,有时不更新,如果更新它更新一些项目并留下其他项目。 这是我的代码:

        recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
        @Override
        public void onItemLongClick(View view, int position) {
            CheckBox checkBox = findViewById(R.id.checkBox);
            checkBox.setVisibility(View.VISIBLE);
            adapter.notifyItemChanged(position);

        }
        }));
        and my listener class is:

public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
public interface OnItemClickListener {
    void onItemClick(View view, int position);

    void onItemLongClick(View view, int position);
}

private OnItemClickListener mListener;

private GestureDetector mGestureDetector;

public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
    mListener = listener;

    mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());

            if (childView != null && mListener != null) {
                mListener.onItemLongClick(childView, recyclerView.getChildAdapterPosition(childView));
            }
        }
    });
}

@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
    View childView = view.findChildViewUnder(e.getX(), e.getY());

    if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
        mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
    }

    return false;
}

@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}

@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}

}

1 个答案:

答案 0 :(得分:0)

我通过在适配器中添加布尔标志解决了我的问题。然后,在onBindViewHolder的方法中,我检查这个标志,并根据它我显示或隐藏项目'复选框如下:

    if(flag){
        holder.itemView.findViewById(R.id.checkBox).setVisibility(View.VISIBLE);
    }

最后在长按方法中我设置了该标志并调用notifyDataSetChanged方法来更新RecycleView的布局如下:

    adapter.flag = true;
    adapter.notifyDataSetChanged();