当点击recylerView中的另一个位置时,setVisibility如何消失所有其他位置?

时间:2018-01-02 07:12:48

标签: android android-recyclerview

我坚持逻辑,无法达到预期的效果。我有一个回收站视图,它有另一个水平子回收站视图。我可以在点击项目时展开折叠视图。我希望当我点击一个元素时,只有当前位置应该扩展所有其他位置才会崩溃。我尝试了很多逻辑,但没有人为我工作。

我的回收站视图适配器代码是:

public class NewAdpater extends RecyclerView.Adapter<NewAdpater.ViewHolder> implements Response.ErrorListener {
    Context context;
    boolean flag=true;
    private List<FetchDocument> docDatalist;
    int customerSerial;
    private int expandedPosition = -1;

    private int vinappserial;
    ImageFetchResponse response;
    ArrayList<Bitmap> bitmaps;
    SendHoldertdata sendHoldertdata;
    UtilityOfActivity utilityOfActivity;
    List<ImageFetchResponseDocumentList> list = new ArrayList<>();


    public NewAdpater(List<FetchDocument> docDatalist, Context context, String vinappserial, SendHoldertdata sendHoldertdata) {

        this.docDatalist = docDatalist;
        this.context = context;
        this.sendHoldertdata = sendHoldertdata;
        utilityOfActivity = new UtilityOfActivity((Activity) context);
        this.vinappserial = Integer.valueOf(vinappserial);
        UserDetail userDetail = new Gson().fromJson(PrefrenceFile.getInstance().getString(Constant.PREF_KEY_USER_DATA), UserDetail.class);
        customerSerial = userDetail.getLoginResponse().getCustInfo().getCustSerialNo();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).
                inflate(R.layout.doc_send_item_list, parent, false);

        ViewHolder viewHolder = new ViewHolder(v);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        holder.recyclerViewImages.setVisibility(View.GONE);
        holder.doc_type.setText(docDatalist.get(position).getDocTypeDesc());

        // expandedPosition=holder.getAdapterPosition();

        holder.myDocumentListCollapse.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                boolean shouldExpand = holder.recyclerViewImages.getVisibility() == View.GONE;
                if (shouldExpand) {
                    holder.recyclerViewImages.setVisibility(View.VISIBLE);

                    holder.iconexpandCollapse.setImageResource(R.mipmap.expand_4);
                    imagerequestserver(docDatalist.get(position), vinappserial, holder);
                    //   DocumentImageFetchResponseListner setData= new DocumentImageFetchResponseListner(holder);

                } else {

                    holder.recyclerViewImages.setVisibility(View.GONE);
                    holder.iconexpandCollapse.setImageResource(R.mipmap.expand);
                }



            }
        });



    }

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

    public interface SendHoldertdata {
        void setdata(ArrayList<Bitmap> bitmapArrayList, int count);
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        TextView doc_type;
        LinearLayout myDocumentListCollapse;
        RelativeLayout layoutAddDoc;
        ImageView iconexpandCollapse;
        RecyclerView recyclerViewImages;

        public ViewHolder(View itemView) {
            super(itemView);
            doc_type = itemView.findViewById(R.id.doc_type);
            myDocumentListCollapse = itemView.findViewById(R.id.myDocumentListCollapse);
            layoutAddDoc = itemView.findViewById(R.id.layoutAddDoc);
            iconexpandCollapse = itemView.findViewById(R.id.iconexpandCollapse);
            recyclerViewImages = itemView.findViewById(R.id.recyclerViewImages);
            recyclerViewImages.setVisibility(View.GONE);
        }

    }

    public void imagerequestserver(FetchDocument fetchDocument, int vinappserial, ViewHolder holder) {

        ImageFetchRequest imageFetchRequest = new ImageFetchRequest();
        imageFetchRequest.setCustSerial(customerSerial);
        imageFetchRequest.setDocGroup(fetchDocument.getDocTypeCode());
        imageFetchRequest.setVehSerial(String.valueOf(vinappserial));
        imageFetchRequest.setDocSerial("0");
        String url = Constant.API_MAIN + Constant.API_DOCUMENT_IMAGEFETCH;
        AbstractVolleyRequest jsonObjectrequest = new
                AbstractVolleyRequest(url, this, new DocumentImageFetchResponseListner(fetchDocument, vinappserial, holder), imageFetchRequest, Request.Method.POST);
        jsonObjectrequest.setTag("DocumentImageFetchRequest");
        Log.v("DocumentFetchRequest", "DocumentImageFetchRequest" + jsonObjectrequest);
        VolleyRequestQue.getmInstance(context.getApplicationContext()).addToRequestQueue(jsonObjectrequest);

    }

    @Override
    public void onErrorResponse(VolleyError error) {
        if (context != null) {
            utilityOfActivity.progresDissmiss();
        }
        utilityOfActivity.toast(context.getString(R.string.connectivity_server_error));
    }

    public class DocumentImageFetchResponseListner extends MyListner<ImageFetchResponse> implements MailDocumentListAdapter.ISelectedImageMail {
        FetchDocument fetchDocument;
        String vinappserial;
        public ViewHolder holder;


        public DocumentImageFetchResponseListner(FetchDocument fetchDocument, int vinappserial, ViewHolder holder) {
            super(ImageFetchResponse.class);
            this.vinappserial = String.valueOf(vinappserial);
            this.fetchDocument = fetchDocument;
            this.holder = holder;
            utilityOfActivity.progressDialogShow(context.getString(R.string.please_wait));
        }


        @Override
        public void onResponse(MyResponse instaResponse) {
            utilityOfActivity.progresDissmiss();
            if (instaResponse != null) {
                if (instaResponse instanceof ImageFetchResponse) {
                    response = (ImageFetchResponse) instaResponse;
                    if (response.getResult().getResultStatus().contains("SUCCESS")) {
                        list = response.getDocumentList();

                        // list.addAll(newList);
                        Log.d("", "");
                        if (list.size() > 0) {
                            setData();

                        }

                    } else {
                        utilityOfActivity.toast(context.getString(R.string.connectivity_server_error));
                    }
                }
            }
        }

        private void setData() {
            MailDocumentListAdapter recyclerViewNewAdpater = new MailDocumentListAdapter(context, list, this);
            holder.recyclerViewImages.setLayoutManager(new GridLayoutManager(context, 3));
            recyclerViewNewAdpater.notifyDataSetChanged();
            holder.recyclerViewImages.setAdapter(recyclerViewNewAdpater);
        }

        @Override
        public void sendBitMap(ArrayList<Bitmap> itemSelectedArrayList,int count) {
            bitmaps = itemSelectedArrayList;
            sendHoldertdata.setdata(bitmaps,count);
        }
    }
}

这是我的DialogFragment,我在其中设置适配器:

public class DialogMailDocument extends DialogFragment implements NewAdpater.SendHoldertdata {
    TextView txtCount;
    int count=0;
    ImageView documentCross;
    RecyclerView recyclerViewDocument;
    UtilityOfActivity utilityOfActivity;
    AppCompatActivity appCompatActivity;
    NewAdpater mainAdapter;
    private int expandedPosition = -1;
    Context mContext;
    ArrayList<Bitmap> sendImageBitmap = new ArrayList<>();
    List<ImageFetchResponseDocumentList> imageFetchResponseDocumentLists;
    List<FetchDocument> fetchDocuments;
    String vinappSerail;
    MailDocumentListAdapter.ISelectedImageMail selectedImageMail;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.fullscreen_dialog);
    }

    private void init(View view) {
        txtCount = view.findViewById(R.id.txtCount);
       // selectAll = view.findViewById(R.id.selectAll);
        recyclerViewDocument = view.findViewById(R.id.recyclerViewDocument);
        TextView tvSendDoc = view.findViewById(R.id.tvSendDoc);
         documentCross = view.findViewById(R.id.documentCross);
        documentCross.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getDialog().dismiss();
            }
        });
        tvSendDoc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (sendImageBitmap != null) {
                    email(getActivity(), "xyz@gmail.com", "hello", sendImageBitmap);
                } else {
                    Toast.makeText(getActivity(), "Nothing is selected", Toast.LENGTH_SHORT).show();
                }
            }
        });

        setDocumentRecyclerView();

    }

    public DialogMailDocument newInstance(MailDocumentListAdapter.ISelectedImageMail iSelectedImageMail) {
        DialogMailDocument fragment = new DialogMailDocument();
        this.selectedImageMail = iSelectedImageMail;
        return fragment;
    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        utilityOfActivity = new UtilityOfActivity(activity);
        appCompatActivity = (AppCompatActivity) activity;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
    }

    @Override
    public void onStart() {
        super.onStart();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_mail_document, container, false);
        Bundle bundle = getArguments();
        if (bundle != null) {
            imageFetchResponseDocumentLists = bundle.getParcelableArrayList("documentList");
            fetchDocuments = bundle.getParcelableArrayList("documentListHead");
            vinappSerail = bundle.getString("vinappSerail");
        }

        init(view);
        return view;
    }

    private void setDocumentRecyclerView() {
        mainAdapter = new NewAdpater(fetchDocuments, getActivity(), vinappSerail, this,expandedPosition);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        recyclerViewDocument.setLayoutManager(mLayoutManager);
        recyclerViewDocument.setAdapter(mainAdapter);
//
//        GridLayoutManager manager =
//                new GridLayoutManager(getActivity(), 3);
//        recyclerViewDocument.setLayoutManager(manager);
//        mainAdapter.setLayoutManager(manager);
//        adapter.shouldShowHeadersForEmptySections(hideEmpty);
//        adapter.shouldShowFooters(showFooters);
        recyclerViewDocument.setAdapter(mainAdapter);
        mainAdapter.notifyDataSetChanged();

    }

    public Uri getImageUri(Context inContext, Bitmap inImage) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
        return Uri.parse(path);
    }

    public void email(Context context, String emailTo, String emailText, ArrayList<Bitmap> filePaths) {
        //need to "send multiple" to get more than one attachment
        final Intent emailIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
        emailIntent.setType("image/*");
        emailIntent.putExtra(Intent.EXTRA_EMAIL,
                new String[]{emailTo});
        emailIntent.putExtra(Intent.EXTRA_TEXT, emailText);
        //has to be an ArrayList
        ArrayList<Uri> uris = new ArrayList<Uri>();
        //convert from paths to Android friendly Parcelable Uri's
        for (Bitmap file : filePaths) {
            Uri u = getImageUri(getActivity(), file);
            uris.add(u);
        }

        emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
        context.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
    }


    @Override
    public void setdata(ArrayList<Bitmap> bitmapArrayList,int count) {
        sendImageBitmap = bitmapArrayList;
        this.count=count;
        txtCount.setText(String.valueOf(count)+" selected");

    }

    @Override
    public void setExpandedPosition(int expandedPosition) {
        DialogMailDocument.this.expandedPosition = expandedPosition;
        mainAdapter.notifyDataSetChanged();
    }
}

4 个答案:

答案 0 :(得分:1)

在模型类中使用布尔值“isShow”,默认情况下将其设置为false,用于Recyclerview的所有项目。

然后...

if (list.get(position).isShow()) {
    // show item....
} else {
    // hide item....
}

在onBindViewHolder方法中迭代一个for循环的最简单方法,如下所示。

for (int i = 0; i < list.size(); i++) {
   if (i == position) {
       if (list.get(position).isShow()) {
           list.get(position).setShow(false);
       } else {
           list.get(position).setShow(true);
       }
   } else {
       list.get(i).setShow(false);
   }
   notifyDataSetChanged();
}

向我询问更多疑问。

感谢。

答案 1 :(得分:0)

您应该在模型类中添加一个布尔变量(默认为false),如果您在单击时打开一个视图,请将该位置的标志设置为true,其余为false。根据这一点,首先检查位置项标志并根据它显示或消失。

答案 2 :(得分:0)

不要在适配器上设置它,而是将展开的孩子position保留在activity(或fragment)上并拨打notifyDataSetChanged()

private int expandedPosition = -1; //just set -1 for default

public NewAdpater(List<FetchDocument> docDatalist, Context context, String vinappserial, SendHoldertdata sendHoldertdata, int expandedPosition) {

    this.docDatalist = docDatalist;
    this.context = context;
    this.sendHoldertdata = sendHoldertdata;
    utilityOfActivity = new UtilityOfActivity((Activity) context);
    this.vinappserial = Integer.valueOf(vinappserial);
    UserDetail userDetail = new Gson().fromJson(PrefrenceFile.getInstance().getString(Constant.PREF_KEY_USER_DATA), UserDetail.class);
    customerSerial = userDetail.getLoginResponse().getCustInfo().getCustSerialNo();
    this.expandedPosition = expandedPosition;
}

...more codes...

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    holder.recyclerViewImages.setVisibility(View.GONE);
    holder.doc_type.setText(docDatalist.get(position).getDocTypeDesc());

    if (expandedPosition == position) {
       holder.recyclerViewImages.setVisibility(View.VISIBLE);
       holder.iconexpandCollapse.setImageResource(R.mipmap.expand_4);
       imagerequestserver(docDatalist.get(position), vinappserial, holder);
    } else {
       holder.recyclerViewImages.setVisibility(View.GONE);
       holder.iconexpandCollapse.setImageResource(R.mipmap.expand);
    }
    // expandedPosition=holder.getAdapterPosition();

    holder.myDocumentListCollapse.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
           sendHoldertdata.setExpandedPosition(position);
        }
    });
}

public interface SendHoldertdata {
    void setdata(ArrayList<Bitmap> bitmapArrayList, int count);

    void setExpandedPosition(int expandedPosition);
}

在你的activity/fragment上(它就是你要通过的expandedPosition):

private int expandedPosition = -1;

@Override
public void onCreate(Bundle saveInstanceState) {
   ...more code
   NewAdpater newAdpater = new NewAdpater(docDataList, context, vinappserial, new SendHoldertdata() {
       @Override
       public void setdata(ArrayList<Bitmap> bitmapArrayList, int count) {
          ...your code
       }

       @Override
       public void setExpandedPosition(int expandedPosition) {
          YourActivityName.this.expandedPosition = expandedPosition;
          newAdpater.notifyDataSetChanged(); //call this to refresh the state, so it will call the onBindViewHolder again on the adapter.
       }
   }, expandedPosition);
}

答案 3 :(得分:0)

这就是你如何做到的。根据此Expendable-Recycler-View,您可以在 parentViewHolder 中添加以下代码。 mArrowExpandImageView是我用来显示展开/折叠图标的imageView,点击它我完成了所有工作。您可以执行类似的操作以获得所需的结果。请查看库中的 ExpendableRecyclerAdapter 类,以便进行扩展和折叠。

  @Override
public void setExpanded(boolean expanded) {
    super.setExpanded(expanded);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        if (expanded) {
            mArrowExpandImageView.setRotation(ROTATED_POSITION);
        } else {
            mArrowExpandImageView.setRotation(INITIAL_POSITION);
        }
    }
}

@Override
public void onExpansionToggled(boolean expanded) {
    super.onExpansionToggled(expanded);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        RotateAnimation rotateAnimation;
        if (expanded) { // rotate clockwise
            rotateAnimation = new RotateAnimation(ROTATED_POSITION,
                    INITIAL_POSITION,
                    RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                    RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        } else { // rotate counterclockwise
            rotateAnimation = new RotateAnimation(-1 * ROTATED_POSITION,
                    INITIAL_POSITION,
                    RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                    RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        }

        rotateAnimation.setDuration(200);
        rotateAnimation.setFillAfter(true);
        mArrowExpandImageView.startAnimation(rotateAnimation);
    }
}

然后在你的片段/活动中,你需要像这样实现展开崩溃监听器:

                yourAdapter.setExpandCollapseListener(new ExpandableRecyclerAdapter.ExpandCollapseListener() {
                @Override
                public void onListItemExpanded(int position) {

                    expendedItemPosition = position;
                    yourAdapter.notifyDataSetChanged();
                }

                @Override
                public void onListItemCollapsed(int position) {

                    expendedItemPosition = -1;
                }
            });