如何在滚动时保持可扩展列表视图中的复选框位置

时间:2016-09-29 07:07:45

标签: android expandablelistview

我正在使用可扩展列表视图,当我向下滚动子项的复选框位置变化时,我想在滚动列表视图时保持该位置。

public class ExpandableListAdapterWork extends BaseExpandableListAdapter {

    // Define activity context
    private Context mContext;
    ArrayList<FilterArray> arrfilter;
    int offsetvalue = 0, limit = 100, count = 0;
    List<String> productList, articleList;
    ArrayList productnamelist, articleOptionList;
    String ProductName, ArticleOption;
    ExpandableListView expandableListView;

    private HashMap<String, List<String>> mListDataChild;

    // ArrayList that is what each key in the above
    // hashmap points to
    private ArrayList<String> mListDataGroup;

    // Hashmap for keeping track of our checkbox check states
    private HashMap<Integer, boolean[]> mChildCheckStates;
    private HashMap<Integer, boolean[]> mProductChildCheckStates;

    private ChildViewHolder childViewHolder;
    private GroupViewHolder groupViewHolder;

    private String groupText;
    private String childText;

    public ExpandableListAdapterWork(Context context, ArrayList<String> listDataGroup, HashMap<String, List<String>> listDataChild, ExpandableListView expandableListView) {

        mContext = context;
        mListDataGroup = listDataGroup;
        mListDataChild = listDataChild;
        productList = new ArrayList<String>();
        productnamelist = new ArrayList();
        arrfilter = new ArrayList<FilterArray>();
        this.expandableListView = expandableListView;
        articleList = new ArrayList<String>();
        articleOptionList = new ArrayList();

        // Initialize our hashmap containing our check states here
        mChildCheckStates = new HashMap<Integer, boolean[]>();
        mProductChildCheckStates = new HashMap<Integer, boolean[]>();
    }

    public int getNumberOfCheckedItemsInGroup(int mGroupPosition) {
        boolean getChecked[] = mChildCheckStates.get(mGroupPosition);
        int count = 0;
        if (getChecked != null) {
            for (int j = 0; j < getChecked.length; ++j) {
                if (getChecked[j] == true) count++;
            }
        }
        return count;
    }

    @Override
    public int getGroupCount() {
        return mListDataGroup.size();
    }

    @Override
    public String getGroup(int groupPosition) {
        return mListDataGroup.get(groupPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }


    @Override
    public View getGroupView(int groupPosition, boolean isExpanded,
                             View convertView, ViewGroup parent) {

        groupText = getGroup(groupPosition);

        if (convertView == null) {

            LayoutInflater inflater = (LayoutInflater) mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.sfilter_list_group, null);

            groupViewHolder = new GroupViewHolder();

            groupViewHolder.mGroupText = (TextView) convertView.findViewById(R.id.lblListHeader);
            groupViewHolder.mImage = (ImageView) convertView.findViewById(R.id.groupImage);
            int imageId = SalesFilterActivity.groupImages.get(groupPosition);
            groupViewHolder.mImage.setImageResource(imageId);

            convertView.setTag(groupViewHolder);
        } else {

            groupViewHolder = (GroupViewHolder) convertView.getTag();
        }

        groupViewHolder.mGroupText.setText(groupText);

        return convertView;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        if (mListDataChild.get(mListDataGroup.get(groupPosition)) != null) {
            return mListDataChild.get(mListDataGroup.get(groupPosition)).size();
        } else {
            return 0;
        }
    }

    @Override
    public String getChild(int groupPosition, int childPosition) {
        try {
            return mListDataChild.get(mListDataGroup.get(groupPosition)).get(childPosition);
        } catch (Exception e) {
            e.printStackTrace();
            return "0";
        }

    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {

        final int mGroupPosition = groupPosition;
        final int mChildPosition = childPosition;

        childText = getChild(mGroupPosition, mChildPosition);

        if (convertView == null) {

            LayoutInflater inflater = (LayoutInflater) this.mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.sfilter_list_item, null);

            childViewHolder = new ChildViewHolder();

            childViewHolder.mChildText = (TextView) convertView
                    .findViewById(R.id.txtdeptname);

            childViewHolder.mCheckBox = (CheckBox) convertView
                    .findViewById(R.id.itemCheckBox);

            convertView.setTag(R.layout.sfilter_list_item, childViewHolder);

        } else {

            childViewHolder = (ChildViewHolder) convertView
                    .getTag(R.layout.sfilter_list_item);
        }

        childViewHolder.mChildText.setText(childText);

        //childViewHolder.mCheckBox.setOnCheckedChangeListener(null);
        convertView.setOnClickListener(null);

        if (mChildCheckStates.containsKey(mGroupPosition)) {

            boolean getChecked[] = mChildCheckStates.get(mGroupPosition);

            if(mChildPosition >= getChildrenCount(mGroupPosition))
            {
            }
            else
            {
                try
                {
                    if(mGroupPosition == 1)
                    {
                        childViewHolder.mCheckBox.setChecked(false);
                    }
                    else {
                        childViewHolder.mCheckBox.setChecked(getChecked[mChildPosition]);
                    }

                }
                catch (Exception e)
                {

                }
                }

        } else {
            Log.e("does not contains grpPos "," "+mGroupPosition);

            boolean getChecked[] = new boolean[getChildrenCount(mGroupPosition)];

            mChildCheckStates.put(mGroupPosition, getChecked);

            childViewHolder.mCheckBox.setChecked(false);
        }
          convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                RelativeLayout rel = (RelativeLayout)v;
                CheckBox cb = (CheckBox) rel.getChildAt(1);
                TextView txtView = (TextView) rel.getChildAt(0);
                String txtSubdept = txtView.getText().toString();//getChild(0,mChildPosition);
                ////Log.e("txtSubDept"," "+txtSubdept);
//
                if(mGroupPosition == 1)
                {
                    Log.e("mChildCheckStates for Group Product"," "+mChildCheckStates.get(1).length);
                    cb.setChecked(true);
                    return;
                }


                if (cb.isChecked() == false) {

                    ////Log.e("checkbox is not selected", "");

                    if (Reusable_Functions.chkStatus(mContext))
                    {

                        //Log.e("mChildCheckStates"," "+mChildCheckStates.get(0).length);
                        SalesFilterActivity.pfilter_list.collapseGroup(1);
                        Reusable_Functions.sDialog(mContext, "Loading  data...");
                        offsetvalue = 0;
                        count = 0;
                        limit = 100;
                        productList = new ArrayList<String>();

                        //Log.e("text value "," "+txtSubdept);
                        requestFilterProductAPI(offsetvalue, limit, txtSubdept);
                        boolean getChecked[] = mChildCheckStates.get(mGroupPosition);
                        getChecked[mChildPosition] = true;
                        mChildCheckStates.put(mGroupPosition, getChecked);
                        cb.setChecked(true);

                    } else {
                        // Reusable_Functions.hDialog();
                        Toast.makeText(mContext, "Check your network connectivity", Toast.LENGTH_LONG).show();
                    }


                } else {
                    ////Log.e("checkbox is  selected", "");
                    ////Log.e("selected text value "," "+txtSubdept);

                    for (int i = 0; i < arrfilter.size(); i++) {
                        if (arrfilter.get(i).getSubdept().equals(txtSubdept)) {
                            SalesFilterActivity.pfilter_list.collapseGroup(1);
                            productnamelist.removeAll(arrfilter.get(i).getprodarray());
                            arrfilter.remove(i);
                            boolean getChecked[] = mChildCheckStates.get(mGroupPosition);
                            getChecked[mChildPosition] = false;
                            mChildCheckStates.put(mGroupPosition, getChecked);
                            cb.setChecked(false);
                            SalesFilterActivity.pfilter_list.expandGroup(1);

                            return;
                        }
                    }



                }
            }
        });


            return convertView;
        }

        @Override
        public boolean isChildSelectable ( int groupPosition, int childPosition){
            return false;
        }

        @Override
        public boolean hasStableIds () {
            return false;
        }

        public final class GroupViewHolder {

            TextView mGroupText;
            ImageView mImage;
        }

        public final class ChildViewHolder {

            TextView mChildText;
            CheckBox mCheckBox;
        }

    public void requestFilterProductAPI(int offsetvalue1, int limit1, final String subdeptName) {

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.mContext);
        String userId = sharedPreferences.getString("userId", "");
        final String bearertoken = sharedPreferences.getString("bearerToken", "");
        Cache cache = new DiskBasedCache(mContext.getCacheDir(), 1024 * 1024); // 1MB cap
        BasicNetwork network = new BasicNetwork(new HurlStack());
        RequestQueue queue = new RequestQueue(cache, network);
        queue.start();
        String url = ConstsCore.web_url + "/v1/display/hourlytransproducts/" + userId + "?view=productName&prodLevel3Desc=" + subdeptName.replaceAll(" ", "%20").replaceAll("&", "%26") + "&offset" + offsetvalue + "&limit" + limit;
        Log.i("URL   ", url);

        final JsonArrayRequest postRequest = new JsonArrayRequest(Request.Method.GET, url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.i("Sub Dept Response", response.toString());
                        try {
                            if (response.equals(null) || response == null || response.length() == 0 && count == 0) {
                                Reusable_Functions.hDialog();
                                Toast.makeText(mContext, "no data found", Toast.LENGTH_LONG).show();
                            } else if (response.length() == limit) {
                                Reusable_Functions.hDialog();

                                for (int i = 0; i < response.length(); i++) {
                                    JSONObject productName1 = response.getJSONObject(i);
                                    ProductName = productName1.getString("productName");
                                    //Log.e("Product Name:", ProductName);

                                    productList.add(ProductName);
                                    productnamelist.add(ProductName);
                                }
                                offsetvalue = (limit * count) + limit;
                                count++;
                                requestFilterProductAPI(offsetvalue, limit, subdeptName);

                            } else if (response.length() < limit) {
                                for (int i = 0; i < response.length(); i++) {
                                    JSONObject productName1 = response.getJSONObject(i);
                                    ProductName = productName1.getString("productName");
                                    //Log.e("Product Name:", ProductName);
                                    productList.add(ProductName);
                                    productnamelist.add(ProductName);
                                }
                                Collections.sort(productnamelist);
                                mListDataChild.put(mListDataGroup.get(1), productnamelist);
                                FilterArray filterArray = new FilterArray();
                                filterArray.setSubdept(subdeptName);
                                filterArray.setprodArray((ArrayList) productList);
                                arrfilter.add(filterArray);
                                SalesFilterActivity.pfilter_list.expandGroup(1);
                                Reusable_Functions.hDialog();
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Reusable_Functions.hDialog();
                        error.printStackTrace();
                    }
                }

        ) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("Content-Type", "application/json");
                params.put("Authorization", "Bearer " + bearertoken);
                return params;
            }
        };
        int socketTimeout = 60000;//5 seconds

        RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        postRequest.setRetryPolicy(policy);
        queue.add(postRequest);

    }

    public void requestProductArticleAPI(int offsetvalue1, int limit1, final String prodName) {

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.mContext);
        String userId = sharedPreferences.getString("userId", "");
        final String bearertoken = sharedPreferences.getString("bearerToken", "");
        Cache cache = new DiskBasedCache(mContext.getCacheDir(), 1024 * 1024); // 1MB cap
        BasicNetwork network = new BasicNetwork(new HurlStack());
        RequestQueue queue = new RequestQueue(cache, network);
        queue.start();

        String url = ConstsCore.web_url + "/v1/display/hourlytransproducts/" + userId + "?view=articleOption&productName=" + prodName.replaceAll(" ", "%20").replaceAll("&", "%26") + "&offset=" + offsetvalue + "&limit=" + limit;
        Log.e("requestProductArticleAPI URL   ", url);

        final JsonArrayRequest postRequest = new JsonArrayRequest(Request.Method.GET, url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.i("requestProductArticleAPI Response", response.toString());
                        try {

                            if (response.equals(null) || response == null || response.length() == 0 && count == 0) {
                                Reusable_Functions.hDialog();
                                Toast.makeText(mContext, "no article data found", Toast.LENGTH_LONG).show();
                            } else {
                                if (response.length() == limit) {

                                    //Reusable_Functions.hDialog();
                                    for (int i = 0; i < response.length(); i++) {
                                        JSONObject productName1 = response.getJSONObject(i);
                                        String ProductName = productName1.getString("productName");
                                        //Log.e("Product Name:", ProductName);
                                        ArticleOption = productName1.getString("articleOption");

                                        //String option = productName.getString("articleOption");
                                        articleList.add(ArticleOption);
                                        articleOptionList.add(ArticleOption);
                                        //Reusable_Functions.progressDialog.cancel();

                                    }
                                    offsetvalue = (limit * count) + limit;
                                    count++;
                                    requestProductArticleAPI(offsetvalue, limit, prodName);
                                } else if (response.length() < limit) {
                                    for (int i = 0; i < response.length(); i++) {
                                        JSONObject productName1 = response.getJSONObject(i);
                                        String ProductName = productName1.getString("productName");
                                        //Log.e("Product Name:", ProductName);
                                        ArticleOption = productName1.getString("articleOption");

                                        //String option = productName.getString("articleOption");
                                        articleList.add(ArticleOption);
                                        articleOptionList.add(ArticleOption);
                                    }
                                    Collections.sort(articleOptionList);
                                    mListDataChild.put(mListDataGroup.get(2), articleOptionList);
                                    FilterArray filterArray = new FilterArray();
                                    filterArray.setprodname(prodName);
                                    filterArray.setArticlearray((ArrayList) articleList);
                                    arrfilter.add(filterArray);
                                    SalesFilterActivity.pfilter_list.expandGroup(2);
                                    Reusable_Functions.hDialog();
                                }
                            }


                        } catch (Exception e) {
                            //Log.e("Exception e", e.toString() + "");
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Reusable_Functions.hDialog();
                        error.printStackTrace();
                    }
                }

        ) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("Content-Type", "application/json");
                params.put("Authorization", "Bearer " + bearertoken);
                return params;
            }
        };
        int socketTimeout = 60000;//5 seconds
        RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        postRequest.setRetryPolicy(policy);
        queue.add(postRequest);
    }
}

我已经完成了。它保留了第一组的位置,我使用了mChildCheckStates但是如果我为其他组位置调用了相同的功能,那么它就不起作用了。如何在滚动时保持复选框位置。

0 个答案:

没有答案